TypeScript · Types that pay for themselves
How is typeof used as a type operator?
Short answer
In a type position, typeof value gives the type of an existing value. It is useful for deriving types from config objects and functions, especially with ReturnType<typeof fn>.
TypeScript has a type-level typeof that is different from the runtime typeof operator. In a type position, it queries the declared type of a value. This lets you derive a type from an implementation instead of maintaining a separate declaration that can drift.
const defaults = {
retries: 3,
timeoutMs: 5000,
};
type Defaults = typeof defaults;
function createClient() {
return { send: () => true };
}
type Client = ReturnType<typeof createClient>;Where it is useful
- Deriving a type from a configuration or constant object
- Extracting a function's return type with ReturnType
- Extracting parameter types with Parameters
- Keeping a type and its runtime value in one place
Without as const, object properties widen, so typeof defaults gives retries: number rather than the literal 3. Add as const when the exact values matter. The type-level typeof only works on values that are in scope; it cannot query a type name that has no value.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1How is type-level typeof different from runtime typeof?
- 2Why does an object type widen without as const?
- 3How do you get a function's return type?
- 4Can typeof query a type alias?
Say it in the interview
typeof in a type position extracts the type of a value. I use it to derive types from configuration objects or functions, often with ReturnType or Parameters. It keeps the type and the implementation from drifting apart. One caveat is that typeof needs a value, and without as const object properties widen to string or number.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live TypeScript mock interview and get scored feedback on depth, clarity and confidence.