What is the difference between typeof in JavaScript and typeof in a type position?
In an expression, typeof returns a string like "number" at runtime. In a type position, typeof x gives the compile-time TypeScript type of the variable x. Same word, different places and different jobs.
Explain it simply
The word typeof does two jobs depending on where it sits. In normal code it runs when the program runs and returns a text label. After a colon or inside a type alias, it is a request to the compiler: "use whatever type this variable already has".
The second use saves you from writing a type twice. Define the value once, and derive its type from it.
Example
const config = { host: "localhost", port: 3000, debug: false };
// Type position: compiler-only
type Config = typeof config;
// { host: string; port: number; debug: boolean }
function start(c: typeof config) {}
// Value position: runtime string
console.log(typeof config.port); // Output: number
console.log(typeof config); // Output: object
function add(a: number, b: number) { return a + b; }
type AddFn = typeof add; // (a: number, b: number) => numberWhat to say in the interview
"In an expression typeof is a runtime check returning a string. In a type position it is a TypeScript operator that reads the type of a value, so I can derive types from objects and functions instead of repeating them. The type form is erased at compile time."
Common mistakes
- Using typeof on a type name; it only accepts values, such as variables and functions.