Array element extraction
Derive an array's item type or preserve a scalar input.
TypeScript · Const
infer captures a type component while a conditional type checks a pattern. The captured variable is usable in the true branch, enabling reusable type-level extraction patterns.
Within the true branch of a conditional type, infer introduces a type variable by matching part of the checked type. The inferred variable can then be used in that branch, allowing reusable type-level patterns such as extracting array elements, function return types, tuple members, or pieces of template literal types.
T extends U ? X : Yinfer in a conditional type to capture a component of a matched type for use in the true branch.Item, represents the part extracted by the matching pattern.infer belongs in a conditional type's extends pattern, not in an ordinary type-parameter constraint.type ElementType<T> = T extends Array<infer Item> ? Item : T;
type A = ElementType<string[]>; // string
type B = ElementType<number>; // number
const values: A[] = ["a", "b"];
console.log(values);The conditional type extracts an array element type and otherwise preserves the input type.
Derive an array's item type or preserve a scalar input.
Capture a function's result type for a utility alias.
Split tuple or template-literal structures into named type components.
infer do in a conditional type?infer declares a type variable inside the extends pattern of a conditional type. If the checked type matches that pattern, the true branch can use the inferred variable; otherwise the false branch is selected.
Follow-up: How would you extract a function's return type? Define T extends (...args: any[]) => infer R ? R : never, then use R in the true branch.
infer extract an array element type?type Flatten<T> = T extends Array<infer Item> ? Item : T matches arrays and binds their element type to Item. For a non-array input, the conditional returns the original type.
Follow-up: How can this be generalized to tuples? Match with a pattern such as T extends [infer Head, ...infer Tail] and use the captured types in the true branch.
For an overloaded function, inference examines the last call signature. The result usually comes from the permissive catch-all signature, and conditional types cannot perform overload resolution from a list of argument types.
Follow-up: What happens when multiple infer locations bind the same variable? TypeScript combines the candidates according to their variance positions, so the resulting type may be a union or intersection.
Conditional typesType inferenceUtility typesTemplate literal types