Syntax
T extends SomePattern<infer U> ? U : neverExamples
Extracting a Function's Return Type
A simplified version of how TypeScript's built-in ReturnType<T> actually works.
type MyReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
function getUser() {
return { id: 1, name: "Alice" };
}
type User = MyReturnType<typeof getUser>;
// User is inferred as: { id: number; name: string }Extracting an Array's Element Type
Unwrapping the inner type from an array or Promise.
type ElementType<T> = T extends (infer Item)[] ? Item : never;
type A = ElementType<string[]>; // string
type B = ElementType<number[]>; // number
type UnwrapPromise<T> = T extends Promise<infer Value> ? Value : T;
type C = UnwrapPromise<Promise<string>>; // stringBest practices
- Use infer specifically when you need to extract and reuse a piece of a matched type, rather than just checking whether it matches
- Study infer through TypeScript's built-in utility types (ReturnType, Parameters, Awaited) - they are the clearest real-world examples of this pattern
- Remember infer can only appear within the extends clause of a conditional type - it has no meaning outside that specific context
- Keep infer-based types well-named and documented, since the syntax itself is dense and can be hard to parse at a glance for readers unfamiliar with it
Runtime & versions
Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
TypeScript Handbook