Sub topic 5
Narrowing Inferred Types with `infer extends`
This chapter assumes you know TypeScript generics, conditional types, tuples, unions, and basic template literal types. You should also know that T extends U ? X : Y chooses X when T is assignable to U; otherwise, it chooses Y.
Why constrain an inferred type?
The infer keyword creates a type variable while TypeScript matches a type pattern. Without a constraint, the inferred variable can be any type that makes the pattern match.
For example, this utility extracts the first tuple element:
type First<T> = T extends [infer Head, ...unknown[]] ? Head : never;
type A = First<[string, number]>; // string
type B = First<[42, boolean]>; // 42Sometimes the utility should succeed only when the captured type has a particular shape. You can add a constraint directly to infer:
type FirstString<T> =
T extends [infer S extends string, ...unknown[]]
? S
: never;
type A = FirstString<["ready", 200]>; // "ready"
type B = FirstString<[200, "ready"]>; // neverinfer S extends string means:
- Match the first tuple element.
- Capture it as
S. - Continue only if
Sextendsstring.
The constraint applies during matching. It does not convert a number into a string.
Compare an unconstrained and constrained match
Consider a utility that extracts a property key from a tuple:
type FirstKey<T> =
T extends [infer K, ...unknown[]]
? K
: never;
type FirstStringKey<T> =
T extends [infer K extends string, ...unknown[]]
? K
: never;
type Unconstrained = FirstKey<[42, "id"]>; // 42
type Constrained = FirstStringKey<[42, "id"]>; // neverThe unconstrained version returns 42, because any type is allowed for K. The constrained version rejects the tuple because its first element is not a string.
This is useful when the true output type depends on a property of the captured value. It prevents a later branch from receiving a type that the utility cannot safely process.
| Pattern | Meaning | Result for `[42, "id"]` |
|---|---|---|
| `infer K` | Capture any first element | `42` |
| `infer K extends string` | Capture only a string first element | `never` |
Constrain function and template matches
Constraints work in other inference positions too. This utility extracts a function's return type only when the return value is an object:
type ObjectReturn<T> =
T extends (...args: any[]) => infer R extends object
? R
: never;
function getUser() {
return { id: 1, name: "Ada" };
}
function getCount() {
return 3;
}
type User = ObjectReturn<typeof getUser>; // { id: number; name: string }
type Count = ObjectReturn<typeof getCount>; // neverThe function itself can have any parameters. Its inferred return type must extend object.
Template literal inference supports the same form:
type FirstSegment<S> =
S extends `${infer Part extends string}.${string}`
? Part
: never;
type A = FirstSegment<"user.name">; // "user"
type B = FirstSegment<"username">; // neverHere, Part must be a string. The constraint is obvious for this example because template literal parts are string-like, but the syntax becomes more useful with unions and more complex patterns.
Choosing a constraint
Use a constraint when an invalid inferred type should make the whole match fail. Choose a broad constraint when several related types are valid, such as object, readonly unknown[], or a union of allowed literals.
A constraint does not replace runtime validation. Conditional types disappear when TypeScript emits JavaScript, so values from external input still need runtime checks.
Exercise
What is the result of FirstString<[boolean, "ok"]>, and why?
Show answer
It is never because the first tuple element is boolean, which does not extend string, so the constrained pattern fails.