The infer keyword
Declaring a type variable inside a conditional's `extends` clause so TypeScript fills it in, to pull element, return and promise types out of other types.
The infer keyword
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- `infer` declares a new type variable inside the `extends` clause of a conditional type; if the match succeeds, TypeScript fills that variable with whatever type sits in that position.
- `infer` only works inside a conditional's `extends` clause, and the variable it declares can only be used in the true branch.
- The pattern on the right of `extends` is a template with holes, so `T extends Promise<infer V>` reads as 'if `T` is a promise of something, call that something `V`'.
- The built-in `ReturnType`, `Parameters` and `Awaited` are written with `infer`; reading their definitions is a good way to learn the pattern.
- Several `infer` variables can appear in one pattern, such as the first element and the rest of a tuple.
- Since TypeScript 4.7, `infer X extends C` adds a constraint, so the match only succeeds when the inferred type also fits `C`.
- Inferring from an overloaded function only sees its last signature, which can surprise you when using `ReturnType` or `Parameters` on overloads.
Getting a type back out
Conditional types can test whether a type has some shape. Often you don’t just want a yes or no, though. You want a part of the type. What is the element type of this array? What does this function return? What does this promise resolve to?
Indexed access types answer some of these. string[][number] gives string. They can’t reach everything, though. There’s no index that gets you a function’s return type, or the type inside a Promise. For those, TypeScript needs a way to say “match this shape, and tell me what was in this slot.”
A pattern with a hole in it
infer is that way. You write the shape you expect on the right of extends, and mark the slot you care about with infer and a name:
type ElementOf<T> = T extends (infer E)[] ? E : never;
type E1 = ElementOf<string[]>; // string
type E2 = ElementOf<(number | null)[]>; // number | null
type E3 = ElementOf<string>; // never
Read T extends (infer E)[] as “if T is an array of something, call that something E.” If T fits the pattern, TypeScript works out what E must be for the match to hold, and E becomes usable in the true branch. If T doesn’t fit, the false branch runs and E doesn’t exist there.
It works like a form with blanks. The pattern is the form, and infer marks a blank. TypeScript lays your type over the form and reads what landed in the blank. When the type doesn’t line up with the form at all, there’s nothing to read.
Two rules follow from this. infer is only allowed in the extends clause of a conditional, because that’s the only place with a pattern to match against. And the inferred variable is only in scope in the true branch, because only there did the match succeed.
type Bad<T> = infer U; // Error: 'infer' declarations are only permitted in the 'extends' clause of a conditional type.
The built-ins are written this way
Several types from the utility types lesson are just infer patterns. Here are hand-written versions:
type MyReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
type MyParameters<T> = T extends (...args: infer P) => any ? P : never;
type Unwrap<T> = T extends Promise<infer V> ? V : T;
function greet(name: string, excited: boolean) {
return excited ? `Hi, ${name}!` : `Hi, ${name}.`;
}
type R1 = MyReturnType<typeof greet>; // string
type P1 = MyParameters<typeof greet>; // [name: string, excited: boolean]
type V1 = Unwrap<Promise<number[]>>; // number[]
type V2 = Unwrap<boolean>; // boolean
The hole can sit anywhere in the pattern: in the return position, around the whole parameter list, or inside a generic’s type argument. The real ReturnType and Parameters constrain T to a function type so that passing a non-function is an error. Awaited goes further than Unwrap by unwrapping nested promises repeatedly, which needs the techniques from recursive types.
The any in these patterns is deliberate. The pattern has to accept every function, and any in parameter position is the simplest way to do that. It never leaks into the result, because the result is whatever got inferred.
Several holes at once
A pattern can contain more than one infer. Tuples are the classic case, using a rest element to split off the head:
type First<T> = T extends [infer Head, ...unknown[]] ? Head : never;
type Rest<T> = T extends [unknown, ...infer Tail] ? Tail : never;
type Split<T> = T extends [infer H, ...infer R] ? { head: H; rest: R } : never;
type F1 = First<[1, 2, 3]>; // 1
type T1 = Rest<[1, 2, 3]>; // [2, 3]
type S1 = Split<["a", true]>; // { head: "a"; rest: [true] }
type F2 = First<[]>; // never
This head-and-tail split is the building block for walking through a tuple one element at a time, which recursive types put to work.
Constraining what gets inferred
Sometimes a match should only count if the inferred piece has a certain type. Since TypeScript 4.7 you can attach a constraint directly to the infer:
type FirstString<T> = T extends [infer S extends string, ...unknown[]]
? S
: never;
type FS1 = FirstString<["id", 2]>; // "id"
type FS2 = FirstString<[1, "id"]>; // never
Without the constraint you’d need a second nested conditional to check S extends string. With it, a first element that isn’t a string makes the whole pattern fail.
One trap with overloads
If you infer from an overloaded function, TypeScript only matches against the last signature:
declare function parse(input: string): number;
declare function parse(input: string[]): number[];
type PR = ReturnType<typeof parse>; // number[]
There is no overload resolution here, because there is no call. The last signature is usually the most general one, so the result is often wider, or just different, from what you expected.
About the video
Matt Pocock’s video opens with the point this lesson rests on: infer has exactly one use, inside the extends clause of a conditional type. From there he works through examples in the style of ReturnType, showing how the pattern on the right of extends decides what gets inferred. Watch it after the first two sections above, when the “pattern with a hole” idea is in place. Andrew Burgess’s video, linked below, is a chaptered tour of four places infer shows up, including generic arguments, arrays, function types and template literals. The Typed Rocks video is a four-minute recap tied to how the built-in helpers are implemented.
Check yourself
What does `ElementOf<boolean[]>` resolve to, given `type ElementOf<T> = T extends (infer E)[] ? E : never`?
`boolean`. `boolean[]` matches the pattern `(infer E)[]`, and the hole marked `infer E` lines up with `boolean`, so `E` is `boolean` in the true branch.
Why is `type Bad<T> = infer U` an error?
`infer` only has meaning inside the `extends` clause of a conditional type, where there is a pattern to match against. Outside that clause there is nothing for TypeScript to match, so it has no way to decide what `U` should be.
How would you write your own version of `ReturnType`?
`type MyReturnType<T> = T extends (...args: any[]) => infer R ? R : never`. The pattern is any function, with the return type left as a hole named `R`; if `T` is a function, `R` is filled with its return type.
What does `infer S extends string` in `T extends [infer S extends string, ...unknown[]] ? S : never` add over plain `infer S`?
It makes the match conditional on the inferred type. If the tuple's first element is a `string`, `S` is inferred and known to be a string in the true branch; if it is anything else, the whole condition fails and the false branch is used.
Why might `ReturnType<typeof f>` give a surprising result when `f` has several overloads?
Inferring from an overloaded function uses only its last signature, usually the most general one. `ReturnType` therefore reports that signature's return type, not the one matching any particular call.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.