What is typeof operator in TypeScript?

Answer

In TypeScript, typeof has two roles. At runtime (JavaScript): it returns a string representing the type of a value ("string", "number", "boolean", "object", "function", "undefined", "symbol", "bigint"). Used for type narrowing: if (typeof x === "string") { x.toUpperCase(); }. At type level (TypeScript-specific): you can use typeof in a type position to extract the type of a variable or expression: const config = { port: 3000, host: "localhost" }; type Config = typeof config; — TypeScript infers Config as { port: number; host: string }. This is especially useful for inferring types from complex objects, arrays, and function return types without manually writing them. Combined with ReturnType<typeof fn> to get a function's return type, or with keyof typeof obj to get the keys of a value as a type.