Sub topic 6
Quick refresher: conditional types and infer
This chapter reviews the two features that the rest of the tutorial uses to take strings apart. You should already be comfortable with these prerequisites:
- Type aliases and generics with constraints, such as
<T extends string>. - String literal types and unions.
- Mapped types of the form
{ [K in keyof T]: ... }.
You do not need prior experience with infer. The chapter covers it from the beginning, including the cases that usually cause confusion.
Conditional types in one paragraph
A conditional type chooses between two types based on a relationship check. It uses the same shape as the ternary operator in JavaScript, but it runs in the type system.
type IsString<T> = T extends string ? true : false;
type A = IsString<"hi">; // true
type B = IsString<42>; // falseThe check T extends string asks whether T is assignable to string. If it is, the result is the first branch. If it is not, the result is the second branch. The compiler evaluates this when T is known, and it replaces the whole expression with one of the two branches.
Evaluation only happens when T is concrete. While T is still an unresolved type parameter, for example inside a generic function body, the compiler leaves the conditional type deferred.
function pick<T>(value: T): T extends string ? number : boolean {
// return 1; // Error: Type 'number' is not assignable to type
// // 'T extends string ? number : boolean'
return (typeof value === "string" ? 1 : false) as T extends string ? number : boolean;
}The compiler cannot know which branch applies, so it refuses to accept a value for either one. A type assertion is the usual workaround. Conditional types fit best in type-level helpers and less well as the return type of runtime functions.
Distribution over unions
When the checked type is a bare type parameter, the conditional type distributes over a union. The compiler runs the check once per union member and unions the results.
type ToArray<T> = T extends unknown ? T[] : never;
type R = ToArray<string | number>; // string[] | number[]The result is not (string | number)[]. The check ran for string and for number separately.
Template literal types rely on the same behavior. Whenever a helper in later chapters accepts a union of strings, it processes each string on its own.
To turn distribution off, wrap both sides of extends in a tuple:
type ToArrayWhole<T> = [T] extends [unknown] ? T[] : never;
type R2 = ToArrayWhole<string | number>; // (string | number)[]Distribution only applies when T appears naked on the left of extends. In [T] extends [unknown], or in Foo<T> extends ..., the parameter is not naked, so nothing distributes.
The never edge case
never is the empty union, so distributing over it runs zero checks and produces never.
type IsString<T> = T extends string ? true : false;
type N = IsString<never>; // never, not falseThis surprises people who expect false. The wrapped form fixes it, and it is the standard way to test for never:
type IsNever<T> = [T] extends [never] ? true : false;
type Y = IsNever<never>; // true
type Z = IsNever<string>; // falseCapturing with infer
The infer keyword declares a new type variable inside the extends clause of a conditional type. If the check succeeds, the compiler fills in the variable with whatever type sat at that position in the checked type. You can then use the variable in the true branch.
type ElementOf<T> = T extends (infer E)[] ? E : never;
type E1 = ElementOf<string[]>; // string
type E2 = ElementOf<(number | null)[]>; // number | null
type E3 = ElementOf<boolean>; // neverThe pattern (infer E)[] reads as "an array of some type, which I will call E". The same idea works for any shape: functions, promises, objects, tuples, and strings.
type ReturnOf<T> = T extends (...args: any[]) => infer R ? R : never;
type PromiseValue<T> = T extends Promise<infer V> ? V : T;
type Fn = ReturnOf<(id: number) => { ok: boolean }>; // { ok: boolean }
type Val = PromiseValue<Promise<string>>; // stringThe standard library ships helpers built this way, including ReturnType, Parameters, and Awaited. Reading their definitions is a good way to practice.
Two rules govern infer:
- You can only write
inferin theextendsclause of a conditional type. - The inferred variable is only in scope in the true branch.
Several infer positions
One pattern can contain many infer variables. Tuples show this well, because the spread syntax lets you peel off elements:
type FirstAndRest<T extends unknown[]> =
T extends [infer F, ...infer R] ? [F, R] : never;
type FR = FirstAndRest<[1, "a", true]>; // [1, ["a", true]]
type Empty = FirstAndRest<[]>; // neverThe empty tuple has no first element, so the pattern fails and the false branch gives never. Template literal patterns behave the same way. A pattern that does not fit produces the false branch, and you decide what that branch returns.
Constraining an inferred variable
Since TypeScript 4.7 you can attach a constraint directly to infer:
type FirstString<T extends unknown[]> =
T extends [infer S extends string, ...unknown[]] ? S : never;
type F1 = FirstString<["a", 1]>; // "a"
type F2 = FirstString<[1, "a"]>; // neverWithout extends string, S would be inferred as "a" or 1 but could not be used where a string is required. With the constraint, the pattern matches only when the first element is a string. The constraint both narrows the type and acts as part of the match.
This feature matters later in the tutorial. When you infer a piece of a string and then need it to be a particular kind of string, infer X extends ... saves a second conditional.
When one variable is inferred in several places
If the same infer name appears more than once, the compiler collects a candidate from each position and combines them. How it combines them depends on the position's variance.
- In a covariant position, such as an object property or a return type, the candidates become a union.
- In a contravariant position, such as a function parameter, 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 FromParams<T> =
T extends { a: (x: infer U) => void; b: (x: infer U) => void } ? U : never;
type Contravariant = FromParams<{
a: (x: string) => void;
b: (x: number) => void;
}>; // never, because string & number has no valuesThe intersection string & number reduces to never. This is the correct answer: a single argument that satisfies both functions would have to be a string and a number at once.
How the compiler decides
The flowchart below shows the evaluation steps for a conditional type with an infer variable.
Each member that comes out of the distribution step goes through the same pattern match as a non-union type does.
A preview with strings
Everything above also works when the pattern is a template literal type. The next chapter covers that in detail, but this short example shows where the refresher leads:
type Prefix<S extends string> = S extends `${infer Head}-${string}` ? Head : S;
type P1 = Prefix<"user-42">; // "user"
type P2 = Prefix<"admin">; // "admin"
type P3 = Prefix<"a-b" | "c-d">; // "a" | "c"Three ideas from this chapter appear here:
- The constraint
S extends stringlets the compiler acceptSinside a template. infer Headcaptures the part before the first hyphen.P3shows distribution. The union"a-b" | "c-d"is checked one member at a time.
Testing your types
Type-level code has no runtime output, so you check it with assertions that fail compilation. This small harness is a common approach, and you can paste it into a file and run it with tsc --noEmit:
type Expect<T extends true> = T;
type Equal<A, B> =
(<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2)
? true
: false;
type ElementOf<T> = T extends (infer E)[] ? E : never;
type IsNever<T> = [T] extends [never] ? true : false;
type Tests = [
Expect<Equal<ElementOf<string[]>, string>>,
Expect<Equal<ElementOf<boolean>, never>>,
Expect<Equal<IsNever<never>, true>>,
Expect<Equal<IsNever<string>, false>>,
];If any Equal returns false, the matching Expect line shows a compile error. Equal is deliberately strict, so any and unknown do not slip through as equal to other types.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Helper returns `never` for `never` input | Distribution over an empty union | Wrap in `[T] extends [never]` before the main check |
| Union result where you wanted one combined type | Distribution over a union | Wrap both sides of `extends` in tuples |
| Inferred variable is `unknown` | The pattern position had no useful information, or the match was too loose | Make the pattern more specific or add `infer X extends ...` |
| Error: `infer` declarations are only permitted in the extends clause | `infer` used outside a conditional type | Move it into a conditional type's `extends` |
| Cannot return a value from a generic function with a conditional return type | The conditional is deferred | Use an overload or a type assertion |
| Type instantiation is excessively deep | A recursive conditional type with no terminating case, or an input that is too large | Add a base case and keep inputs small |
The last row comes up again in the final chapter of this tutorial, where recursion limits are covered in full.
Summary of the model
- A conditional type tests
T extends Uand returns one of two types. - A naked type parameter distributes over unions.
neverproducesnever. - Tuple wrapping turns distribution off.
infernames a piece of the matched type. The name exists in the true branch only.- Repeated names merge candidates: a union from covariant positions, an intersection from contravariant ones.
infer X extends Cconstrains the captured type and makes the match stricter.
Exercise
Predict the result of each type, then explain the difference. type Box<T> = T extends unknown ? { value: T } : never; type BoxWhole<T> = [T] extends [unknown] ? { value: T } : never; type One = Box<"a" | "b">; type Two = BoxWhole<"a" | "b">;
Show answer
One is { value: "a" } | { value: "b" }, because Box has a naked T on the left of extends and therefore distributes over the union, producing one object type per member. Two is { value: "a" | "b" }, because the tuple wrapper stops distribution and the whole union is checked once.
Exercise
Write a type LastElement<T extends unknown[]> that returns the last element of a tuple type, or never for an empty tuple. Then give the result for LastElement<[1, "a", true]> and LastElement<[]>.
Show answer
type LastElement<T extends unknown[]> = T extends [...unknown[], infer L] ? L : never; LastElement<[1, "a", true]> is true. LastElement<[]> is never, because an empty tuple has no final element, so the pattern does not match and the false branch applies.
Exercise
What does this type evaluate to, and why? type Both<T> = T extends { x: (v: infer U) => void; y: (v: infer U) => void } ? U : never; type Result = Both<{ x: (v: "a" | "b") => void; y: (v: "b" | "c") => void }>;
Show answer
Result is "b". U is inferred from function parameters, which are contravariant positions, so the candidates are intersected: ("a" | "b") & ("b" | "c") reduces to "b".