Sub topic 7
Extracting types with infer
This chapter assumes you can write generic type aliases with constraints and that you know the basic form of a conditional type, T extends U ? X : Y. You should also be comfortable reading function types, tuples, and Promise<T>.
What infer does
A conditional type can only ask whether a type matches a pattern. The infer keyword lets the pattern capture a piece of the matched type under a name. You can then use that name in the true branch.
type MyReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
type ElementOf<T> = T extends readonly (infer U)[] ? U : never;
type R = MyReturnType<() => Promise<string>>; // Promise<string>
type E = ElementOf<number[]>; // numberIn MyReturnType, the pattern is "a function that takes any arguments and returns something". The infer R part marks that "something" as a variable for the compiler to solve. If T is assignable to the pattern with some value of R, the true branch runs with that value. Otherwise the false branch runs.
Think of infer as pattern matching on types. You write a shape with holes, and the compiler fills the holes.
Where infer can appear
You can put infer anywhere inside the right-hand side of extends where a type is allowed. These are the positions you will use most.
| Position | Pattern | Captures |
|---|---|---|
| Function return | `(...args: any[]) => infer R` | Return type |
| Function parameters | `(...args: infer P) => any` | Parameter tuple |
| Array element | `readonly (infer U)[]` | Element type |
| Generic argument | `Promise<infer U>` | Type argument |
| Object property | `{ id: infer I }` | Property type |
| Tuple slot | `[infer H, ...infer Rest]` | Individual elements or the remainder |
| Template literal | `` `${infer Head}.${infer Rest}` `` | String pieces |
You can only declare infer inside the extends clause of a conditional type. Writing it in a plain alias, such as type X<T> = infer U, is a compile error. The inferred name is also only in scope in the true branch. You cannot use it in the false branch.
Parameters and tuples
Capturing the parameters of a function gives you a labeled tuple.
type MyParameters<T> = T extends (...args: infer P) => any ? P : never;
type Args = MyParameters<(a: string, b: number) => void>;
// [a: string, b: number]Tuples can be split with infer in the same way you destructure arrays at runtime.
type Head<T extends readonly unknown[]> =
T extends readonly [infer H, ...unknown[]] ? H : never;
type Tail<T extends readonly unknown[]> =
T extends readonly [unknown, ...infer Rest] ? Rest : never;
type FirstItem = Head<[1, 2, 3]>; // 1
type Others = Tail<[1, 2, 3]>; // [2, 3]
type Nothing = Head<[]>; // neverThe empty tuple does not match [infer H, ...unknown[]] because that pattern requires at least one element, so the false branch gives never.
Objects and promises
Matching an object type pulls out one property type without needing a key lookup.
type IdOf<T> = T extends { id: infer I } ? I : never;
type UserId = IdOf<{ id: number; name: string }>; // number
type NoId = IdOf<{ name: string }>; // neverExtra properties do not stop the match, because the pattern only requires that id exists.
A single unwrap step for promises looks like this. When T is not a promise, the false branch returns T unchanged, which is usually better than never for an unwrapper.
type UnwrapPromise<T> = T extends Promise<infer U> ? U : T;
async function fetchUser() {
return { id: 1, name: "Ada" };
}
type UserResult = UnwrapPromise<MyReturnType<typeof fetchUser>>;
const user: UserResult = { id: 2, name: "Grace" };
console.log(user.name);Here MyReturnType<typeof fetchUser> is Promise<{ id: number; name: string }>, and UnwrapPromise strips the Promise. The built-in Awaited<T> does the same job and also handles nested promises. A later chapter rebuilds it recursively.
Several infer sites for one name
You can use the same name more than once. The compiler then collects a candidate from every site and combines them. How it combines them depends on the variance of each position.
- In covariant positions, such as property types and return types, the candidates become a union.
- In contravariant positions, such as function parameters, the candidates become an intersection.
type FromProps<T> = T extends { a: infer U; b: infer U } ? U : never;
type Covariant = FromProps<{ a: string; b: number }>;
// string | number
type FromHandlers<T> = T extends {
a: (x: infer U) => void;
b: (x: infer U) => void;
}
? U
: never;
type Contravariant = FromHandlers<{
a: (x: { p: 1 }) => void;
b: (x: { q: 2 }) => void;
}>;
// { p: 1 } & { q: 2 }The intersection result depends on strictFunctionTypes, which is on under strict. With it off, parameter positions are treated bivariantly and the result can differ. Intersection behavior is the basis of the well-known "union to intersection" helper, so it is worth recognizing when you see it.
Constraining an inferred type
Since TypeScript 4.7 you can attach a constraint directly to the inferred variable with infer U extends ....
type FirstNumber<T> = T extends [infer N extends number, ...unknown[]]
? N
: never;
type Good = FirstNumber<[1, "a"]>; // 1
type Bad = FirstNumber<["a", 1]>; // neverThe constraint becomes part of the match. If the captured element is not a number, the whole pattern fails and you get the false branch. Before 4.7 you needed a nested conditional to get the same effect.
The same syntax is useful with template literals, where captured pieces are otherwise always string.
type ParseInt<S extends string> = S extends `${infer N extends number}`
? N
: never;
type Port = ParseInt<"8080">; // 8080
type Word = ParseInt<"hello">; // neverRecursion with infer
Because an inferred part is just a type, you can feed it back into the same alias. Splitting a string on a separator is a standard example.
type Split<S extends string> =
S extends `${infer Head}.${infer Rest}` ? [Head, ...Split<Rest>] : [S];
type Parts = Split<"a.b.c">; // ["a", "b", "c"]For "a.b.c", Head is matched against the shortest prefix before the first ., so it is "a" and Rest is "b.c". The recursion ends when no . remains and the false branch wraps the last piece.
Gotchas and failure modes
Overloads: only the last signature counts
When a function has several overloads, inference against a function pattern uses the last one.
declare function parse(x: string): number;
declare function parse(x: number): string;
type ParseReturn = ReturnType<typeof parse>; // stringThe first overload is ignored. If you need all of them, you have to write each signature by hand or restructure the code to avoid overloads.
Generic functions lose their type parameters
A generic function is not matched with its type parameters intact. The compiler replaces each type parameter with its constraint.
type Identity = <T>(x: T) => T;
type IdentityReturn = ReturnType<Identity>; // unknownYou get unknown because that is the constraint of T. If you see unexpected unknown from an extractor, check whether the source function is generic.
Silent never
Most extractors end in : never. A type that does not match produces never with no error, and never then flows through the rest of your types. When a helper returns never for input that should work, test the pattern against the input one piece at a time. For example, check T extends (...args: any[]) => any before adding the infer.
Distribution over unions
When T is a bare type parameter, an extractor distributes over unions.
type Results = MyReturnType<(() => string) | (() => number)>;
// string | numberThat is usually what you want for extractors. Wrap both sides in tuples, [T] extends [...], if you need the check to apply to the union as a whole. The next chapters cover that case.
Arrays and readonly
T extends (infer U)[] does not match a readonly array, because a readonly array is not assignable to a mutable one. Use readonly (infer U)[] in the pattern, as ElementOf does above. It matches both kinds.
Summary of the working model
- Write the shape you expect on the right of
extends. - Replace the parts you want with
infer Name. - Use
Namein the true branch, and choose a sensible false branch (neverto signal failure,Tto pass through unchanged). - Add
extendsconstraints toinfervariables when the captured part must have a certain kind.
Exercise
Write a type Last<T> that returns the last element of a tuple type T, and never for an empty tuple. What do Last<[1, 2, 3]> and Last<[]> evaluate to?
Show answer
Use a leading rest element in the pattern: type Last<T extends readonly unknown[]> = T extends readonly [...unknown[], infer L] ? L : never. Last<[1, 2, 3]> is 3, because L captures the final slot. Last<[]> is never, because an empty tuple has no final slot to match.
Exercise
Given declare function f(x: string): number; and declare function f(x: number): boolean;, what is ReturnType<typeof f>, and why?
Show answer
It is boolean. When inference runs against an overloaded function, TypeScript uses only the last overload signature, so the first overload that returns number is ignored.
Exercise
Why does type Bad<T> = T extends (infer U)[] ? U : never return never for a readonly string[] argument, and how do you fix it?
Show answer
A readonly array is not assignable to a mutable array type, so the pattern does not match and the false branch runs. Change the pattern to readonly (infer U)[], which matches both mutable and readonly arrays.