The typeof Type Operator
The typeof Type Operator — the core idea
In a type position, typeof captures the static type of a value or declaration. In an expression position, JavaScript typeof returns a runtime string such as "number". The two operators share spelling but serve different purposes.
What you’ll learn
- Explain the typeof type operator with a concrete use case.
- Run the example and account for every line of its output.
- Recognize the difference between compile-time checking and runtime behavior.
Understand the rules and when to use them
Reading the code: The type query creates Config from config's shape without executing additional code. backup must have retries:number and mode:string. At runtime typeof backup.retries evaluates to the string "number".
Keep the boundary clear: typeof config does not preserve every value as a literal automatically; add as const to keep readonly literal properties when appropriate.
See the idea as a flow
Run the complete TypeScript example
Save the code as typeof-type-operator.ts. The result below was captured after compiling this exact example with strict TypeScript checking and executing the emitted JavaScript in Node.js.
TypeScript code
const config = { retries: 3, mode: "safe" };
type Config = typeof config;
const backup: Config = { retries: 5, mode: "fast" };
console.log(backup.retries);
console.log(typeof backup.retries);Verified output
5
numberBuild: npx tsc --strict --target es2022 --module commonjs --lib es2022,dom,esnext.disposable typeof-type-operator.ts; run: node typeof-type-operator.js. The exact filename may be changed freely. When a multi-file project exists, prefer its tsconfig.json and build scripts.
Trace the example line by line
The type query creates Config from config's shape without executing additional code. backup must have retries:number and mode:string. At runtime typeof backup.retries evaluates to the string "number".
The output shown above comes from the initialized values in this program. Replacing a type annotation alone does not transform a JavaScript value.
Avoid this common mistake
typeof config does not preserve every value as a literal automatically; add as const to keep readonly literal properties when appropriate.
Check both the TypeScript diagnostic and the emitted JavaScript behavior. A program can compile correctly and still need runtime validation or error handling.
Practice independently
Create a settings object, infer its type with typeof, and define a second object conforming to it.
Before running your change, write down the type you expect TypeScript to infer and the output you expect JavaScript to print. Then check both predictions.
Check your understanding
What to remember
In a type position, typeof captures the static type of a value or declaration.
Try the practice change and re-run the exact program to test your understanding.
Reaching the recap and completing the quizzes are separate milestones.