Sub topic 5
Narrowing inferred types with infer extends
This chapter covers the infer U extends C form, which captures part of a type and also requires that part to satisfy a constraint. It assumes you know generics, tuple types, template literal types (basic syntax), and the plain infer keyword from the earlier chapters. The examples need TypeScript 4.7 or later. The number-parsing example needs 4.8 or later.
The problem: an inferred type starts out as unknown
A bare infer U places no restriction on U. Inside the true branch, TypeScript treats U as unknown, so you cannot pass it to anything that expects a narrower type.
type FirstOf<T> = T extends [infer H, ...unknown[]] ? H : never;
type Greeting<T> = T extends [infer H, ...unknown[]]
? `Hello, ${H}` // error: Type 'H' is not assignable to type 'string | number | bigint | boolean | null | undefined'
: never;The error appears because a template literal only accepts primitive types, and H could be anything. Before TypeScript 4.7, the usual workaround was a second conditional inside the first:
type Greeting<T> = T extends [infer H, ...unknown[]]
? H extends string
? `Hello, ${H}`
: never
: never;That works, but the nesting grows quickly. It also hides a design decision: whether a non-string head means "no match" or "match with a different result".
The syntax: infer U extends C
TypeScript 4.7 lets you attach a constraint directly to the inferred variable.
type FirstString<T> = T extends [infer S extends string, ...unknown[]] ? S : never;
type X = FirstString<['a', 1, 2]>; // 'a'
type Y = FirstString<[1, 'a']>; // neverThe constraint does two things:
- Inside the true branch,
Sis known to be astring, so you can use it where a string is required. - The match only succeeds if the inferred type satisfies the constraint. If it does not, the whole
extendscheck fails and the conditional takes the false branch.
The second point is the one that surprises people. The constraint is part of the question "does T match this pattern?". It does not just annotate the variable after the fact.
Failure is a false branch, not an error
A failed constraint never produces a compile error. It selects the false branch, and in most utility types that branch is never. That makes the constraint a filter.
type EventName<T> = T extends `on${infer E extends 'click' | 'hover'}` ? E : never;
type A = EventName<'onclick'>; // 'click'
type B = EventName<'onscroll'>; // never
type C = EventName<'onclick' | 'onhover' | 'onscroll'>; // 'click' | 'hover'Here the constraint is a union of literals. The string 'onscroll' has the right shape (on followed by some text), but the inferred text 'scroll' is not assignable to 'click' | 'hover', so it is rejected. The third line shows distribution at work: each union member is checked on its own, and the rejected one contributes never, which disappears from the result union.
Using the false branch as the next case
Because a failed constraint falls through, you can chain patterns, much like a switch.
type Describe<T> =
T extends [infer H extends string, ...unknown[]] ? `string:${H}`
: T extends [infer H extends number, ...unknown[]] ? `number:${H}`
: 'other';
type D1 = Describe<['a', 0]>; // 'string:a'
type D2 = Describe<[42]>; // 'number:42'
type D3 = Describe<[true]>; // 'other'Both the string and number branches use the inferred head directly in a template literal. That is legal only because each H carries a primitive constraint.
Comparing the approaches
| Approach | Where the check happens | Result when the check fails |
|---|---|---|
| `infer U` then a nested `U extends C ? ... : ...` | After the match succeeded | You choose, in the nested false branch |
| `infer U extends C` | During the match | The outer false branch runs |
| Constraining the type parameter (`T extends C`) | At the call site | A compile error for the caller |
Constraining the type parameter and constraining an inferred variable solve different problems. A parameter constraint rejects bad input. An infer constraint filters which parts of valid input you accept.
Parsing strings into numbers
The constraint has a second use with template literals. Since TypeScript 4.8, writing infer N extends number inside a template makes TypeScript try to convert the matched text into a number literal type.
type ToNumber<S extends string> = S extends `${infer N extends number}` ? N : never;
type N1 = ToNumber<'42'>; // 42
type N2 = ToNumber<'abc'>; // neverWithout the constraint, infer N in that position would give you the string '42'. With it, you get the numeric literal 42. When the text is not a valid number, the constraint fails and you get never.
The same rule applies when the pattern has several parts.
type Point<S extends string> = S extends `${infer X extends number},${infer Y extends number}`
? [X, Y]
: never;
type P = Point<'3,4'>; // [3, 4]
type Q = Point<'3,y'>; // neverEach variable has its own constraint, and every one must pass for the true branch to run.
Constraining variables in other positions
You can place a constrained infer anywhere a plain infer is allowed. A common case is a function parameter.
type FirstParamIfString<F> =
F extends (first: infer P extends string, ...rest: any[]) => any ? P : never;
declare function greet(name: string, times: number): void;
declare function repeat(count: number): void;
type G = FirstParamIfString<typeof greet>; // string
type R = FirstParamIfString<typeof repeat>; // neverFor repeat, the candidate for P is number, which is not assignable to string, so the match fails.
Constraints on a rest element work too. For example, T extends [infer H, ...infer Rest extends string[]] matches only when everything after the head is a string.
Common errors
- Targeting an older compiler. On a version before 4.7,
infer U extends Cis a syntax error. Checktsc --versionand your editor's bundled TypeScript version, because they can differ. - Expecting a compile error from a failed constraint. You will get the false branch instead. If your utility silently returns
never, check whether an inferred variable failed its constraint. - Over-narrowing the constraint. If you write
infer N extends 1 | 2, then3is rejected even though it is a number. Choose the widest constraint that gives the guarantees you need. - Forgetting that unions are checked whole. In
FirstString<['a' | 1, 2]>, the head is'a' | 1. That union is not assignable tostring, so the result isnever, not'a'. Distribution only splits a union that is the checked type itself, such asFirstString<['a'] | [1]>. - Constraining something you do not need to. If you only pass the inferred type along unchanged, a bare
infer Uis simpler and has fewer ways to fail.
Why this matters for the next chapters
Recursive types such as string splitters and tuple walkers depend on pattern matching that fails cleanly. A constraint like infer N extends number lets a recursive parser reject malformed input at the point where it appears, instead of carrying an unchecked unknown through every level of recursion.
Exercise
Write a type FirstNumber<T> that returns the first element of a tuple T when that element is a number, and never otherwise. What do FirstNumber<[5, 'a']>, FirstNumber<['a', 5]>, and FirstNumber<[]> evaluate to?
Show answer
Use type FirstNumber<T> = T extends [infer N extends number, ...unknown[]] ? N : never. FirstNumber<[5, 'a']> is 5, because the head is 5 and it satisfies number. FirstNumber<['a', 5]> is never, because the head 'a' fails the constraint. FirstNumber<[]> is never, because the empty tuple does not match the pattern, which needs at least one element.
Exercise
Given type Level<S extends string> = S extends level-${infer N extends number} ? N : never, what are Level<'level-3'>, Level<'level-high'> and Level<'level-1' | 'level-2'>? Which compiler version is the minimum for this to behave as shown?
Show answer
Level<'level-3'> is 3, because the text '3' converts to the number literal 3. Level<'level-high'> is never, because 'high' cannot convert to a number and the constraint fails. Level<'level-1' | 'level-2'> is 1 | 2, because S is a naked type parameter and the conditional distributes over the union. The minimum version is TypeScript 4.8, which added number conversion for infer extends number in template literals.