TypeScript · Types that pay for themselves
What does the infer keyword do?
Short answer
infer declares a type variable inside the extends clause of a conditional type. It extracts part of a type, such as a function's return value or a promise's resolved value.
infer lets a conditional type capture a type that is not named in advance. You write a pattern such as Promise<infer Value> and the compiler solves for Value when the condition matches. The inferred variable is available only in the true branch.
type UnwrapPromise<T> =
T extends Promise<infer Value> ? Value : T;
type A = UnwrapPromise<Promise<number>>;
type Return<T> =
T extends (...args: never[]) => infer R ? R : never;
type B = Return<() => string>;Where infer is used
- Extracting a promise's resolved type
- Extracting a function's return or parameter types
- Reading the first element of a tuple
- Building parsers and schema types from a runtime shape
- Implementing utility types such as ReturnType and Parameters
Multiple infer positions are allowed, but the compiler must be able to solve them from the matched type. Inference in a contravariant position, such as a function parameter, can behave differently from inference in a covariant position. When the result is surprising, isolate the pattern in a small type and test it.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Where can infer be used?
- 2How do you extract a promise's resolved type?
- 3What happens when infer appears in a function parameter position?
- 4How does ReturnType use infer?
Say it in the interview
infer lets me capture a type inside a conditional type. I use it to extract a promise's resolved value, a function's return type or a tuple's first element. The inferred variable is only in scope in the true branch. It is the mechanism behind many utility types, but I avoid stacking many infer clauses because the resulting errors become hard to read.
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.