← TypeScript

Advanced · 1 of 12 · 14 min read

Conditional types

An if-statement for types — how extends is read as a question, why a union distributes across it, and the idioms that turn that into real work.

  • Conditional types

A conditional type is a ternary that runs in the type system. It is the point where types stop being descriptions and start being computation — and almost every utility type in the standard library is one.

The shape

type IsString<T> = T extends string ? "yes" : "no";

type A = IsString<string>;   // "yes"
type B = IsString<number>;   // "no"
type C = IsString<"hello">;  // "yes" — a literal is assignable to string

const a: A = "yes";
const b: B = "no";
const c: C = "yes";
console.log(a, b, c); // "yes" "no" "yes"

The extends here is the assignability test behind every error message the compiler produces, which is why a string literal passes a extends string check, and why the special types behave oddly:

type Check<T> = T extends string ? 1 : 2;

type A = Check<any>;      // 1 | 2 — `any` goes both ways
type B = Check<never>;    // never — see the distributivity section
type C = Check<unknown>;  // 2

const c: C = 2;
console.log(c);

Distributivity

This is the part that surprises people, and the part that makes conditionals useful:

type ToArray<T> = T extends unknown ? T[] : never;

type A = ToArray<string | number>;
// NOT (string | number)[]
// It is string[] | number[]

const a: A = ["x"];
console.log(a);

The conditional distributed: it ran with T = string, then with T = number, and unioned the two results. That only happens when the checked type is a naked type parameter — T on its own, not wrapped in anything.

That is the whole implementation of the union filters:

type MyExclude<T, U> = T extends U ? never : T;
type MyExtract<T, U> = T extends U ? T : never;
type MyNonNullable<T> = T extends null | undefined ? never : T;

type Role = "admin" | "user" | "guest";
type A = MyExclude<Role, "admin">;      // "user" | "guest"
type B = MyNonNullable<string | null>;  // string

const a: A = "user";
const b: B = "x";
console.log(a, b);

Read MyExclude<Role, "admin"> member by member: "admin" becomes never, "user" stays, "guest" stays. Then never | "user" | "guest" collapses — never is the empty type, so it vanishes from a union. Filtering a union is mapping every member either to itself or to nothing.

Turning distributivity off

Wrap both sides in a one-element tuple and T is no longer naked:

type Naked<T> = T extends string ? true : false;
type Wrapped<T> = [T] extends [string] ? true : false;

type A = Naked<string | number>;    // boolean — true | false, distributed
type B = Wrapped<string | number>;  // false — asked once, about the whole union

const b: B = false;
console.log(b);

[T] extends [string] asks the question once, about the union as a whole. Use it whenever the answer should be about the type you were handed rather than about each of its parts — an IsUnion, an IsNever, an equality check.

The never case is the one that bites:

type IsNeverWrong<T> = T extends never ? true : false;
type IsNever<T> = [T] extends [never] ? true : false;

type A = IsNeverWrong<never>;  // never — there were no members to distribute over
type B = IsNever<never>;        // true

const b: B = true;
console.log(b);

never is the empty union. Distributing over it means iterating zero members, so the result is never — not true, and not an error. Every never-detecting type has to be written with the tuple wrapper.

Written as On a union Use for
T extends U ? X : Y distributes, member by member filtering and mapping a union
[T] extends [U] ? X : Y asked once, about the whole asking about the type itself
T extends unknown ? F<T> : never distributes deliberately forcing distribution
T[] extends U[] ? X : Y does not distribute T is not naked

Nesting, as a dispatch table

Chained conditionals read like a switch:

type TypeName<T> =
  T extends string ? "string" :
  T extends number ? "number" :
  T extends boolean ? "boolean" :
  T extends undefined ? "undefined" :
  T extends Function ? "function" :
  "object";

type A = TypeName<() => void>;  // "function"
type B = TypeName<Date>;        // "object"

const a: A = "function";
const b: B = "object";
console.log(a, b);

Order matters, exactly as in a switch: the first matching branch wins, so the most specific test comes first. T extends object ahead of T extends Function would swallow the function case, because a function is an object structurally.

Unwrap-if-wrapped

The single most common conditional in real code:

type Flatten<T> = T extends readonly (infer Item)[] ? Item : T;

type A = Flatten<string[]>;  // string
type B = Flatten<number>;    // number — not an array, passed through

const a: A = "x";
const b: B = 1;
console.log(a, b);

Awaited, Flatten, and every “accept a value or a getter” helper have this shape: match the wrapper, pull the payload out with infer, and otherwise leave the type alone.

Deferred evaluation

Inside a generic function, a conditional whose T is not yet known stays unresolved — and nothing is assignable to an unresolved conditional:

type Wrap<T> = T extends string ? { text: T } : { value: T };

function wrap<T>(input: T): Wrap<T> {
  // return typeof input === "string" ? { text: input } : { value: input };
  // Not assignable to Wrap<T> — the compiler cannot evaluate it yet.
  return (typeof input === "string" ? { text: input } : { value: input }) as Wrap<T>;
}

console.log(wrap("a"), wrap(1)); // { text: "a" } { value: 1 }

The assertion is the accepted answer here, and it is one of the few places an as is honest: a conditional return type is a promise the implementation has to keep, and the type system has no way to check the body against it. Keep such a body small enough to read in one go.

Recursion

Conditionals can call themselves, which is how a deep transformation is expressed:

type DeepReadonly<T> = T extends (infer Item)[]
  ? readonly DeepReadonly<Item>[]
  : T extends object
    ? { readonly [K in keyof T]: DeepReadonly<T[K]> }
    : T;

interface Config { server: { host: string; ports: number[] } }

const c: DeepReadonly<Config> = { server: { host: "x", ports: [1] } };
// c.server.host = "y";     // Cannot assign to 'host'
// c.server.ports.push(2);  // push does not exist on a readonly array
console.log(c.server.host, c.server.ports[0]);

Note the order: the array branch comes first because an array also satisfies extends object, and mapping over an array as if it were a plain object loses its arrayness.

Common mistakes

Reading extends as inheritance

Mistake. Expecting T extends Animal to be false for a plain object with the right shape. Why it fails. It is an assignability test, and the type system is structural — the object passes. What to do instead. Read it as “fits where a U is expected”. For a nominal test, a branded type or a private member is the tool.

Forgetting the tuple wrapper on a never check

Mistake. type IsNever<T> = T extends never ? true : false. Why it fails. never is the empty union, so distribution iterates nothing and the result is never rather than true. What to do instead. [T] extends [never] — and the same wrapper for any question about the type as a whole.

Accidental distribution

Mistake. A conditional meant to classify a type, handed a union, returning a union of classifications. Why it fails. The naked parameter distributed, so TypeName<string | number> is "string" | "number" rather than one answer. What to do instead. Wrap in a tuple when you want one answer; leave it naked when you want the map.

Check yourself

4 questions from the bank on what you just read. Answering here does not affect your quiz history.

A conditional type is an if in the type system, resolved by assignability.

What are A and B?

Code sample
type IsString<T> = T extends string ? "yes" : "no";

type A = IsString<string>;
type B = IsString<number>;

What does it mean that conditional types are *distributive*?

Distributivity has one edge case that catches everyone the first time.

Why is Result never rather than "no"?

Code sample
type IsString<T> = T extends string ? "yes" : "no";

type Result = IsString<never>;

Why would you write T extends U ? X : Y with U as unknown[]?

Practise Conditional types →

Further reading

Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.

Reaching the end of a lecture marks it as read.