Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 96 ยท Type Manipulation

Conditional Types

Learn TypeScript conditional types - T extends U ? X : Y, how they distribute over unions, how to stop that with [T], and how infer extracts types.

Mapped types let a type loop over keys. Conditional types let a type make a decision. They have the shape T extends U ? X : Y, which reads "if T is assignable to U, the result is X, otherwise Y". It's the ternary operator from JavaScript, moved to the type level.

On their own, conditionals look like a curiosity. Their real power comes from two extra features. They distribute over unions, so a conditional applied to A | B | C runs once per member, which is how Exclude and Extract filter unions. And the infer keyword lets a conditional pull a type out of another type: the element type of an array, the return type of a function, the value inside a promise. ReturnType, Parameters and Awaited from the utility types lesson are all built this way, and by the end of this lesson you'll have written each of them yourself.

As in the previous lessons, examples prove their results with type _t = Expect<Equal<Actual, Expected>>; (introduced in Built-in Utility Types). A run that prints its last line means every check passed.

The basic form

The condition T extends U uses the same rule as assignment: it's true when a value of type T could be assigned to a variable of type U. So 'hello' extends string is true, number extends string is false, and { id: 1; name: 'x' } extends { id: number } is true (extra properties are fine, as you know from type compatibility).

TypeScript A first conditional type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

IdOf already uses infer, which gets its own section below. The chained TypeName reads top to bottom like an if/else if ladder; the first matching branch wins. Formatting each condition on its own line keeps long chains readable.

Conditional types in function signatures

A conditional type can describe a function whose return type depends on the argument type. Here, passing a string gives back a string and passing a number gives back a number, and callers see the precise result:

TypeScript A return type that depends on the input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Why the two signatures? Inside a generic function body, T is still unknown, so TypeScript can't decide Doubled<T> and won't accept a plain string or number as a value of that type. Returning value.repeat(2) from a function declared to return Doubled<T> fails with error TS2322. The usual solutions are an overload like this one (the public signature is generic, the implementation signature is simple) or a type assertion on the returned value. For only two or three cases, plain overloads without a conditional type are often clearer.

Distribution over unions

Here's the behavior that surprises everyone the first time. When the checked type is a bare type parameter and you pass a union, the conditional is applied to each member separately, and the results are joined back into a union:

TypeScript Distributive conditional types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Walk through MyExclude<Status, 'idle'>: TypeScript evaluates 'idle' extends 'idle' ? never : 'idle' (gives never), then 'loading' extends 'idle' ? never : 'loading' (gives 'loading'), and so on. Joining the results gives never | 'loading' | 'success' | 'error', and never vanishes from unions. That's the whole implementation of the built-in Exclude.

Note the difference between string[] | number[] (an array of only strings or an array of only numbers) and (string | number)[] (a mixed array). Distribution produced the first one. The union types lesson compares the two in detail.

Turning distribution off

Distribution only happens when the left side of extends is a naked type parameter. Wrap both sides in a one-element tuple and the union is checked as a whole:

TypeScript Stopping distribution with brackets

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The IsNever example shows a classic trap. never behaves like a union with zero members, so distributing over it runs the conditional zero times and the result is never, not true or false. Any time you test for never, wrap the check in brackets.

any is a special case too. IsString<any> is boolean, because TypeScript evaluates both branches when the checked type is any and joins them. Conditional types are one more reason to prefer unknown over any (see any, unknown, never and void).

Extracting types with infer

Inside the extends clause, infer Name declares a new type variable and asks TypeScript to work out what it must be for the match to succeed. You can then use Name in the true branch. It's pattern matching for types: describe the shape, and mark the part you want to capture.

TypeScript infer captures part of a type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

A few rules about infer:

  • It's only allowed inside the extends clause of a conditional type.
  • If the pattern doesn't match (like First<[]>, where there is no first element), the false branch is used.
  • You can use several infer variables in one pattern, for example T extends [infer A, infer B] ? [B, A] : never swaps a pair.
  • The parentheses in readonly (infer E)[] are required: readonly infer E[] is a syntax error (TS1005).

Why never[] in the function pattern?

MyReturnType matches against (...args: never[]) => infer R. That pattern must accept every function, whatever its parameters. Because function parameters are checked contravariantly, a function that takes (id: number) is assignable to one that takes never arguments, but not to one that takes unknown arguments. The standard library uses any[] in the same place; never[] achieves the same thing without writing any.

Constraints on infer

Since TypeScript 4.7 you can constrain an inferred type with infer X extends Constraint. The match only succeeds if the captured type satisfies the constraint. This is especially handy with template literal types, which can parse a string literal into a number:

TypeScript infer with extends constraints

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

PropOf combines distribution and infer: it runs once per member of Events, captures the property's type where it exists, and returns never (which disappears) where it doesn't. You'll take string parsing much further in Template Literal Types.

Recursive conditional types

A conditional type can refer to itself. That's how you unwrap structures of any depth, such as nested arrays or promises inside promises:

TypeScript Recursion with conditional types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

MyAwaited checks against PromiseLike rather than Promise, so it also unwraps any "thenable" object with a then method, just like await does. The real Awaited adds a few more details (for example, it handles null and undefined), but the idea is the same.

TypeScript limits how deep recursion can go. Type aliases that recurse in a tail position (the recursive call is the whole result of a branch, as in both examples above) are optimized and can go about 1,000 levels deep. Others hit a much lower limit (a non-tail-recursive type 100 levels deep already fails) and report error TS2589, "Type instantiation is excessively deep and possibly infinite". The advanced type-level programming lesson has more on keeping recursive types fast.

When conditional types are deferred

If a conditional type's checked type is still a generic parameter, TypeScript can't pick a branch yet, so it defers the type and keeps it as written. That's what happened inside double() above. Deferred conditionals are normal; they resolve as soon as callers supply real types. The practical rules:

  • At call sites, conditional types work great: the caller's argument types are known.
  • Inside generic implementations, expect to need an overload or an assertion to produce a value of a conditional type.
  • If a conditional only ever chooses between two or three fixed shapes, overloads or a discriminated union are often simpler for readers.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given type F<T> = T extends string ? 's' : 'n', what is F<string | number>?

    T is a naked type parameter, so the conditional distributes, giving 's' for string and 'n' for number.
  2. 2. What is [T] extends [unknown] ? T[] : never when T is string | number?

    Wrapping T in a tuple stops distribution, so the union is checked as a whole and becomes a single mixed array type.
  3. 3. Why does type IsNever<T> = T extends never ? true : false give never for IsNever<never>?

    A distributive conditional over the empty union produces the empty union, never. Use [T] extends [never] instead.
  4. 4. What is T extends [infer A, infer B] ? [B, A] : never for T = [1, 'x']?

    infer captures A = 1 and B = 'x' from the pair, and the true branch puts them in reverse order.
  5. 5. Where can you write infer?

    infer declares a type variable to be matched, which only makes sense in the pattern after extends in a conditional type.

Summary

  • T extends U ? X : Y picks X when T is assignable to U, otherwise Y. Chain conditionals for multi-way decisions.
  • When the checked type is a naked type parameter, conditionals distribute over unions; Exclude, Extract and NonNullable are built on this.
  • Wrap both sides in brackets, [T] extends [U], to check a union as a whole. Always test for never this way.
  • infer X captures part of a matched type (array elements, function returns and parameters, tuple members, promise values); infer X extends C adds a constraint.
  • Conditional types can be recursive (DeepElement, MyAwaited); tail-recursive ones can go much deeper.
  • Inside generic function bodies, conditional types are deferred, so implementations need overloads or assertions.

Next: Template Literal Types