What is typeof operator in TypeScript?
Why Interviewers Ask This
Foundational questions like this help interviewers calibrate the rest of the interview. A confident, accurate answer signals that you have solid TypeScript basics — a prerequisite for any developer role.
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.
Pro Tip
Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a TypeScript codebase.
Previous
What is the keyof operator in TypeScript?
Next
What is the difference between type and interface in TypeScript?