Sub topic 3
Capturing a type with infer
This chapter assumes you know TypeScript generics, union and tuple types, and the basic syntax of a conditional type (T extends U ? X : Y). Earlier chapters covered how extends picks a branch and how conditionals distribute over unions. Here you learn the infer keyword, which lets a conditional type name part of the type it is checking and reuse that part in its result.
The problem infer solves
A plain conditional type can only ask a yes/no question. It can tell you that string[] is an array, but it cannot hand you the element type. You could write one conditional for each element type you expect, but that does not scale.
infer solves this. Inside the extends clause, you put infer U where a type would normally go. TypeScript treats that spot as a hole. If the checked type fits the pattern, TypeScript fills the hole with whatever type sits there and binds it to the name U.
type ElementType<T> = T extends (infer U)[] ? U : never;
type A = ElementType<string[]>; // string
type B = ElementType<number>; // neverReading ElementType<string[]> step by step:
- TypeScript checks whether
string[]is assignable to(infer U)[]. - To make that check, it solves for
U. The only value that works isstring. - The check succeeds, so the true branch runs with
U = string.
For number, no value of U makes number look like an array. The check fails and the false branch gives never.
Where infer is allowed and where its name is visible
infer is only legal in the extends clause of a conditional type. The name it declares is visible only in the true branch.
// Error: 'infer' declarations are only permitted
// in the 'extends' clause of a conditional type.
type Bad1<T> = infer U;
// Error: Cannot find name 'U'. U does not exist in the false branch.
type Bad2<T> = T extends (infer U)[] ? U : U;Think of infer U as a variable declaration whose scope is the true branch. If you need a value in the false branch, use the original T or a type parameter with a default.
type ElementOr<T, Fallback = T> = T extends readonly (infer U)[] ? U : Fallback;
type C = ElementOr<string[]>; // string
type D = ElementOr<number>; // number (Fallback defaults to T)
type E = ElementOr<number, 'not an array'>; // 'not an array'Notice readonly (infer U)[] in this version. The reason is covered in the gotchas below.
Patterns you can match against
The pattern after extends can be any type shape, and you can place infer anywhere a type can appear inside it. The next chapter surveys function, tuple and Promise positions in detail. Here are a few simple shapes to build intuition.
An object property:
type IdOf<T> = T extends { id: infer I } ? I : never;
type I1 = IdOf<{ id: number; name: string }>; // number
type I2 = IdOf<{ name: string }>; // neverA generic type's arguments. You can infer more than one variable in a single pattern:
type MapEntry<T> = T extends Map<infer K, infer V> ? [K, V] : never;
type M = MapEntry<Map<string, number>>; // [string, number]The first element of a tuple, ignoring the rest:
type Head<T extends unknown[]> = T extends [infer H, ...unknown[]] ? H : never;
type H1 = Head<[1, 2, 3]>; // 1
type H2 = Head<[]>; // neverThe Head<[]> case is worth noticing. An empty tuple has no first element, so it does not match [infer H, ...unknown[]]. The false branch runs, and the result is never.
What happens when the match is loose
infer fills the hole with the best type the compiler can find. That type is not always the narrowest one you hoped for.
type ElementType<T> = T extends (infer U)[] ? U : never;
type T1 = ElementType<[1, 'a']>; // 1 | 'a'
type T2 = ElementType<any[]>; // any
type T3 = ElementType<never[]>; // neverA tuple [1, 'a'] is assignable to an array of 1 | 'a', so U becomes the union of all the element types. If you wanted the tuple's first element, you needed the Head pattern, which spells out the tuple shape.
Inference from any and unknown follows the input. If the thing in the hole is any, U is any. When you see surprising any in a result, trace it back to the input type first.
Using the same variable more than once
You can write infer U with the same name in several places in one pattern. TypeScript collects one candidate per place and combines them. In covariant positions, such as property types and array elements, the combined result is a union.
type Both<T> = T extends { a: infer U; b: infer U } ? U : never;
type X = Both<{ a: string; b: number }>; // string | numberThis is useful when you want "any of these". It is also a common source of surprise, because you may expect the match to fail when the two properties have different types. It does not fail. The union is a valid solution, so the check succeeds.
Function parameters are a contravariant position, and there the candidates combine into an intersection instead. A later chapter on multiple candidates covers that case. For now, remember that "same name, several places" means "combine the candidates", and the combining rule depends on the position.
Interaction with distribution
When the checked type is a bare type parameter, the conditional distributes over unions. That applies to conditionals with infer as well. Each union member is checked separately, and each gets its own U.
type ElementType<T> = T extends (infer U)[] ? U : never;
type U1 = ElementType<string[] | number[]>; // string | number
type U2 = ElementType<string[] | number>; // stringIn U2, the number member goes to the false branch and contributes never. A union with never collapses to the other member, so you get string. If you need to prevent distribution, wrap both sides of extends in tuples ([T] extends [(infer U)[]]). Then the whole union is checked as one unit.
type ElementTypeStrict<T> = [T] extends [(infer U)[]] ? U : never;
type U3 = ElementTypeStrict<string[] | number[]>; // string | number
type U4 = ElementTypeStrict<string[] | number>; // neverU3 is string | number because string[] | number[] as a whole is assignable to (string | number)[]. U4 is never because string[] | number is not assignable to any array type.
Common errors and gotchas
The following table lists the problems you are most likely to hit.
| Symptom | Cause | Fix |
|---|---|---|
| `ElementType<readonly string[]>` is `never` | A `readonly` array is not assignable to a mutable array pattern | Match `readonly (infer U)[]`. Mutable arrays are assignable to it. |
| Error: `infer` declarations are only permitted in the `extends` clause | `infer` used outside the pattern | Move it into the right-hand side of `extends`. |
| Error: Cannot find name `U` | Using the variable in the false branch or outside the conditional | Use it only in the true branch. |
| Result is a union when you expected a failure | Same variable in two covariant positions | Use two different names and compare them, or constrain the pattern. |
| Result is `unknown` | Nothing in the checked type pinned down the hole | Check that the pattern really mentions the position you want. |
| Result is `never` for a union input | Distribution sent some members to the false branch | Wrap in `[T] extends [...]` to disable distribution. |
The readonly row deserves a short demonstration, because it affects many real utilities.
type Mutable<T> = T extends (infer U)[] ? U : never;
type Either<T> = T extends readonly (infer U)[] ? U : never;
type R1 = Mutable<readonly string[]>; // never
type R2 = Either<readonly string[]>; // string
type R3 = Either<string[]>; // stringIf you write a utility that should accept any array, use the readonly form in the pattern. It accepts both kinds.
Putting it together
Here is a small utility that uses what this chapter covered. It extracts the resolved value type from a Promise and leaves other types alone. It uses one infer, a fallback in the false branch, and no distribution surprises for plain inputs.
type PromiseValue<T> = T extends Promise<infer V> ? V : T;
type P1 = PromiseValue<Promise<string>>; // string
type P2 = PromiseValue<number>; // number
type P3 = PromiseValue<Promise<number> | boolean>; // number | boolean
type P4 = PromiseValue<Promise<Promise<number>>>; // Promise<number>P4 shows the limit of this version. It unwraps one layer only. Handling any depth requires the type to refer to itself, which is the subject of the recursion chapters later in this tutorial.
Exercise
Write a type SetItem<T> that returns the item type of a Set, and never for anything that is not a Set. What are SetItem<Set<boolean>> and SetItem<boolean[]>? Then explain why SetItem<Set<string> | Set<number>> gives string | number.
Show answer
type SetItem<T> = T extends Set<infer U> ? U : never;. SetItem<Set<boolean>> is boolean. SetItem<boolean[]> is never, because an array does not match Set<...>. Because T is a bare type parameter, the conditional distributes over the union. Set<string> gives string, Set<number> gives number, and the results combine into string | number.
Exercise
Given type Pair<T> = T extends { first: infer A; second: infer B } ? [A, B] : never;, what is Pair<{ first: 1; second: 'x'; extra: true }>? What would change if you used infer A in both places instead of infer A and infer B?
Show answer
The result is [1, 'x']. Extra properties do not stop the match, because an object with more properties is still assignable to the pattern. If both places used infer A, the candidates 1 and 'x' would combine into the union 1 | 'x', and the result would be [1 | 'x', 1 | 'x'].
Exercise
type First<T> = T extends (infer U)[] ? U : never; returns never for readonly [1, 2]. Change the pattern so it accepts readonly arrays too, and say what the result is for readonly [1, 2].
Show answer
Use T extends readonly (infer U)[] ? U : never. A readonly tuple is assignable to a readonly array, so the check passes. U is the union of the element types, so the result is 1 | 2. To get only the first element, use a tuple pattern such as T extends readonly [infer H, ...unknown[]] ? H : never, which gives 1.