Sub topic 12
Extracting Types with `infer`
Prerequisites
This chapter assumes that you know basic TypeScript types, union types, type aliases, and conditional types. A conditional type chooses one type when a condition is true and another when it is false:
type IsString<T> = T extends string ? true : false;
type A = IsString<"hello">; // true
type B = IsString<42>; // falseConditional types are evaluated by the TypeScript compiler. They do not run in JavaScript.
What `infer` Does
The infer keyword creates a temporary type variable while TypeScript checks whether a type matches a pattern. You can then use that variable in the true branch of a conditional type.
The general form is:
type Result<T> = T extends SomePattern<infer U> ? U : Fallback;Here, U represents the part of T that matches the pattern.
For example, this type extracts the element type from an array:
type ElementType<T> = T extends (infer U)[] ? U : T;
type TextElement = ElementType<string[]>; // string
type NumberElement = ElementType<number[]>; // number
type PlainNumber = ElementType<number>; // numberFor string[], TypeScript matches the array pattern (infer U)[] and sets U to string. For number, the pattern does not match, so the type uses the false branch and returns number.
Extracting Function Types
You can use infer to extract a function's return type or parameter types.
type FunctionResult<T> =
T extends (...args: never[]) => infer R ? R : never;
function getMessage(): string {
return "Ready";
}
function getCount(): number {
return 3;
}
type Message = FunctionResult<typeof getMessage>; // string
type Count = FunctionResult<typeof getCount>; // number
type NotAFunction = FunctionResult<boolean>; // nevertypeof getMessage means “the type of this function.” The conditional type checks whether that type is callable. If it is, infer R captures the return type as R.
TypeScript provides the same idea through the built-in ReturnType utility type:
type MessageAgain = ReturnType<typeof getMessage>; // stringYou can also infer a function's argument tuple:
type ParametersOf<T> =
T extends (...args: infer P) => unknown ? P : never;
function createUser(name: string, age: number): boolean {
return name.length > 0 && age >= 18;
}
type UserArguments = ParametersOf<typeof createUser>; // [string, number]P captures all parameters as a tuple. A tuple is an array type whose positions have known types.
Extracting Nested Types
infer can match nested structures. This example extracts the resolved value from a promise-like type:
type UnwrapPromise<T> =
T extends Promise<infer U> ? U : T;
type LoadedUser = UnwrapPromise<Promise<{ id: number }>>;
// { id: number }
type AlreadyLoaded = UnwrapPromise<string>; // stringThe built-in Awaited<T> utility type handles this problem in real applications and also unwraps nested promises.
A Common Limitation
When a type can have several forms, decide what the fallback should be. Returning never communicates that the input does not match, while returning T preserves nonmatching values.
Exercise
What is the result of type Item<T> = T extends (infer U)[] ? U : never when T is boolean[]?
Show answer
boolean. The array matches the pattern, so infer U captures the element type.