TypeScript Conditional Types Explained: The Complete Guide

2026-12-05来源 dev.toEnglish

You write a type alias meant to wrap anything in an array: type ToArray<T> = T extends any ? T[] : never. Feed it string, you get string[]. Feed it string | number, you reasonably expect (string | number)[]. What you actually get is string[] | number[] — a union of two separate array types, not a single array of the union. The alias is correct. TypeScript is correct. You've just run into distribution, one of the specific, learnable rules behind conditional types — the mechanism TypeScript uses to compute a type that depends on another type, the way an if/else computes a value that depends on a condition.

What you'll learn

By the end of this guide you'll be able to:

  • Read and write a conditional type (T extends U ? X : Y) and say exactly what it evaluates to
  • Predict when a conditional type distributes over a union, and switch it off on purpose with a one-line change
  • Use infer to pull a type out of a larger shape — a function's return type, an array's element type, a promise's resolved value
  • Explain why infer sometimes unions the types it captures and sometimes intersects them
  • Recognize the handful of built-in utility types (Exclude, Extract, NonNullable, ReturnType, Awaited) that are themselves just conditional types, and know the recursion limit that keeps a self-referential one honest

Who this is for: you've written and used generic types in TypeScript — plain Array<T>-style generics, maybe Partial<T> or Exclude<T, U> — and you want to understand what's actually happening inside them instead of treating them as fixed vocabulary.

Contents

  • Why conditional types exist
  • The mental model: a type-level if/else, evaluated per union member
  • Stage 1: the basic conditional type
  • Stage 2: distribution over unions
  • Stage 3: infer — pulling a type out of a shape
  • Stage 4: the built-in utility types are conditional types
  • Edge cases and gotchas
  • Best practices
  • FAQ
  • Cheat sheet
  • Key takeaways

Why conditional types exist

Before conditional types (TypeScript 2.8), a generic type had exactly one shape, no matter what you fed it. If you wanted "the element type of an array, or the type itself if it isn't an array," you had no way to express that as a single reusable type — you wrote one overload per case, or you gave up and typed the result as any.

// what you want to express: "unwrap an array, otherwise pass the type through" // there is no way to say this with a plain generic alias type Unwrap<T> = T; // always just T — no branching available 

Conditional types close that gap by letting a type alias branch on a relationship between two types, the same way a function branches on a runtime value:

type Unwrap<T> = T extends (infer U)[] ? U : T; type A = Unwrap<string[]>; // string type B = Unwrap<number>; // number — not an array, passes through unchanged 

That's the shape of every conditional type in this guide: a check (T extends (infer U)[]), a type for when it holds (U), and a type for when it doesn't (T).

The mental model: a type-level if/else, evaluated per union member

The mental model: T extends U ? X : Y is evaluated the moment the compiler needs a concrete answer for a specific T — not once per generic declaration, but once per actual type you substitute in. And when that substituted T is a union, and T is a "naked" type parameter in the check (not buried inside an array, a tuple, or an object), the compiler doesn't test the union as a whole — it distributes: it tests each member of the union separately, then unions the results back together.

type IsString<T> = T extends string ? "yes" : "no"; type Single = IsString<number>; // "no" type FromUnion = IsString<string | number>; // "yes" | "no" — tested member by member, then unioned 

Key concept: a conditional type with a naked type parameter doesn't run once against a union — it runs once per member of that union, and the results are joined with |. This single rule is responsible for almost every "surprising" conditional type result you'll hit, including the opening example.

Stage 1: the basic conditional type

The syntax is exactly T extends U ? TrueBranch : FalseBranch. extends here isn't inheritance — it's a compatibility check: "is every value of type T assignable to type U?"

type IsNumber<T> = T extends number ? true : false; type A = IsNumber<42>; // true type B = IsNumber<"42">; // false 

You can chain these like else if, and TypeScript resolves them top to bottom, same as a runtime if/else if/else:

type TypeName<T> = T extends string ? "string" : T extends number ? "number" : T extends boolean ? "boolean" : T extends undefined ? "undefined" : "object"; type X = TypeName<42>; // "number" type Y = TypeName<() => void>; // "object" — falls through every branch above it 

Generic parameters can also be constrained inside the condition, which is how most real conditional types are written — T is usually a type parameter of the alias itself:

type ElementOf<T extends readonly unknown[]> = T[number]; type Item = ElementOf<["a", "b", "c"]>; // "a" | "b" | "c" 

Stage 2: distribution over unions

This is the stage that causes the most confusion, because the rule is narrow and easy to miss: distribution only happens when the checked type is a bare, unwrapped type parameter — T extends U ? X : Y where T is exactly the thing you passed in, with nothing around it.

type ToArray<T> = T extends any ? T[] : never; type Result = ToArray<string | number>; // string[] | number[] — NOT (string | number)[] 

Walk it the way the compiler does: it doesn't ask "does string | number extend any?" once. It splits the union, asks the question for string (yes → string[]), asks it again for number (yes → number[]), and unions the two answers. That's the entire mechanism — there's no separate "union mode," just the same rule applied one member at a time.

To get the "whole union, not per-member" behavior, wrap both sides of the extends in a tuple. A tuple containing a union is not itself a union, so there's nothing left for the compiler to distribute over:

type ToArrayNonDist<T> = [T] extends [any] ? T[] : never; type Result2 = ToArrayNonDist<string | number>; // (string | number)[] — the union is now a single array 

🎮 Try it yourself

▶️ Open the interactive playground →

Runs right in your browser — poke at it and watch the concept react live.

Neither version is "the bug" — they answer genuinely different questions. ToArray answers "give me an array type for each member of this union." ToArrayNonDist answers "give me one array type for the whole union." Pick the one your use case actually needs, deliberately, rather than discovering the difference in a type error later.

Stage 3: infer — pulling a type out of a shape

infer can only appear inside the extends clause of a conditional type. It introduces a new type variable that the compiler fills in by pattern-matching the shape on the left against the shape on the right — the same way destructuring pulls a value out of an object at runtime, except this happens at the type level, at compile time.

type ReturnTypeOf<T> = T extends (...args: any[]) => infer R ? R : never; type R1 = ReturnTypeOf<() => string>; // string type R2 = ReturnTypeOf<(x: number) => boolean>; // boolean type R3 = ReturnTypeOf<string>; // never — not a function, falls to the else branch 

Key concept: infer R doesn't check anything by itself — it's a placeholder that says "whatever type ends up in this position, call it R and make it available in the true branch." The actual check is still the surrounding extends.

The same pattern works against any structural shape, not just function calls:

type ElementType<T> = T extends (infer U)[] ? U : T; type Flat = ElementType<number[]>; // number type PromiseValue<T> = T extends Promise<infer V> ? V : T; type Val = PromiseValue<Promise<string>>; // string 

infer can appear more than once if the shape has more than one slot to capture — the same variable inferred from two different properties of the type being checked, for instance. When the same inferred variable shows up in more than one position, TypeScript has to pick a single type for it, and where those positions sit changes how it combines them: a covariant position (something you read, like a property) unions the candidates; a contravariant position (something you write to, like a function parameter) intersects them. "Edge cases and gotchas" below walks through a concrete pair of these — it's worth re-reading once you've seen the real example.

Stage 4: the built-in utility types are conditional types

Exclude, Extract, and NonNullable — the ones you've probably already used — are not special compiler magic. They're ordinary distributive conditional types, defined in TypeScript's own standard library:

type Exclude<T, U> = T extends U ? never : T; type Extract<T, U> = T extends U ? T : never; type NonNullable<T> = T extends null | undefined ? never : T; 

Read Exclude<T, U> with the distribution rule from Stage 2 in mind: for each member of T, if it's assignable to U, replace it with never; otherwise keep it. A union with any never members simplifies away automatically, because never contributes nothing to a union — which is exactly why this one line is enough to filter a union down to the members you want:

type Status = "idle" | "loading" | "success" | "error"; type Settled = Exclude<Status, "idle" | "loading">; // "success" | "error" 

ReturnType<T> and Parameters<T> are the infer pattern from Stage 3, already shipped for you:

type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any; type Parameters<T extends (...args: any) => any> = T extends (...args: infer P) => any ? P : never; 

Awaited<T> (added in TypeScript 4.5, and the type behind every await expression and async function's inferred return type) is the same idea made recursive — it has to unwrap a Promise<Promise<Promise<string>>> down to string, not just one layer, and it also has to handle any "thenable" object, not only the real Promise class. The real definition guards against a non-callable .then and a few other edge cases; the shape of it is this:

type MyAwaited<T> = T extends Promise<infer V> ? MyAwaited<V> : T; type A = MyAwaited<Promise<Promise<string>>>; // string type B = MyAwaited<number>; // number — not a promise, returned as-is 

A conditional type referring to itself in its own true branch is legal — TypeScript has allowed recursive conditional types since version 4.1 — and it's exactly how you unwrap an arbitrarily nested shape without knowing the nesting depth in advance.

Edge cases and gotchas

Distribution vanishes the moment the type parameter isn't naked. T extends U ? X[] : Y distributes (the checked type, T, is bare); Record<string, T> extends U ? X : Y does not, because T is no longer the thing directly being checked — it's buried inside Record. If a conditional type you expected to distribute isn't, check that the type parameter sitting right before extends is truly unwrapped.

A distributive conditional type with never as the input returns never, immediately — not the false branch. never is the empty union: zero members. Distributing an operation over zero members produces zero results, i.e. never, regardless of what the true or false branch says:

type IsString<T> = T extends string ? "yes" : "no"; type Weird = IsString<never>; // never — not "no" 

This is intentional, and it's the reason Exclude<T, U> correctly produces never (not some other fallback) when you exclude every member of T — the empty-distribution rule is doing the filtering, not a special case written into Exclude.

infer in a contravariant position intersects instead of unions. Capture the same infer variable from two properties you'd read, and TypeScript unions the candidates — the ordinary, covariant case:

type PropType<T> = T extends { a: infer U; b: infer U } ? U : never; type FromRead = PropType<{ a: string; b: number }>; // string | number 

Capture it from two function parameters instead — positions you write to, not read from — and TypeScript intersects the candidates:

type ParamType<T> = T extends { a: (x: infer U) => void; b: (x: infer U) => void } ? U : never; type FromWrite = ParamType<{ a: (x: string) => void; b: (x: number) => void }>; // never 

A function parameter is contravariant: a value typed to accept either caller's argument has to accept both, which is an intersection, not a union. Here that intersection is string & number — a type with no possible values — and modern TypeScript simplifies that impossible combination straight down to never, correctly reflecting that no single parameter type can satisfy both call signatures at once.

Recursive conditional types have a depth limit. TypeScript bounds how many times it will re-instantiate a self-referential conditional type before giving up, to catch genuinely infinite types (a mistake, not a feature) rather than hang the compiler. Push a recursive type too deep — iterating character-by-character over a very long string literal type, for instance — and you'll see Type instantiation is excessively deep and possibly infinite. The exact depth isn't a number worth memorizing or relying on; treat the error as a sign to add a base case or rethink the recursion, not as a limit to work around.

Best practices

Reach for a conditional type when a generic alias genuinely needs to answer different questions depending on what's passed in — unwrapping a container type, deriving one type from the shape of another, or filtering a union. That's precisely what infer, distribution, and the built-ins in Stage 4 are for.

Avoid them when a plain union, a mapped type, or an overloaded function signature says the same thing more simply. A conditional type is a tool for deriving a type from another type's shape — if you're not deriving anything, you're adding a branch for the sake of having one.

Decide distribution on purpose. Before shipping a conditional type generic over a type parameter, ask whether it should answer "per union member" or "for the union as a whole," and write [T] extends [U] explicitly when you mean the latter — don't let it be an accident you discover from a confusing inferred type three call sites away.

Give a recursive conditional type an explicit base case and keep the accumulator bounded. MyAwaited above terminates because every recursive step strips one Promise<> layer and the non-promise branch doesn't recurse; a conditional type that can't guarantee it's making progress toward a non-recursive case is the one that hits the depth limit.

FAQ

Why does my conditional type behave differently for a union than for a single type?

Because the checked type parameter is "naked" (not wrapped in an array, tuple, or object), so TypeScript distributes the conditional over each union member and unions the results — see "Stage 2: distribution over unions."

How do I stop a conditional type from distributing?

Wrap both sides of the extends clause in a one-element tuple: [T] extends [U] ? X : Y. A tuple containing a union isn't itself a union, so there's nothing left to distribute over.

What does infer actually do?

It introduces a new type variable inside an extends clause and lets the compiler fill it in by matching the surrounding shape — the function's return type, an array's element type, a promise's resolved value — against the type being checked. The check that triggers the match is still the ordinary extends relationship; infer only names what gets captured.

Is T extends U ? X : Y resolved immediately, or can it stay unresolved?

When T is a concrete type, it resolves immediately. When T is still a type parameter whose concrete value isn't known yet (inside a generic function body, for example), the conditional type stays deferred — unevaluated — until something substitutes a real type for T.

Are Exclude, Extract, and ReturnType special compiler features?

No — they're ordinary conditional types defined in TypeScript's bundled type-declaration files, built from exactly the same extends/infer syntax covered in this guide. You can read their real definitions, and you could write equivalents yourself.

Cheat sheet

Pattern Example What it does
Basic branch T extends U ? X : Y Type-level if/else on assignability
Chained branches T extends A ? "a" : T extends B ? "b" : "c" Evaluated top to bottom, like else if
Distributive (naked T) T extends any ? T[] : never Runs once per union member, unions the results
Non-distributive [T] extends [any] ? T[] : never Runs once for the whole union
Capture with infer T extends (infer U)[] ? U : T Pulls a type out of a matched shape
infer in covariant position Same infer read from two properties Unions the captured candidates
infer in contravariant position Same infer written via two function parameters Intersects the candidates (often collapsing to never)
never through a distributive type IsString<never> Distributing over zero members gives never, always
Recursive conditional type Awaited<T> Legal since TS 4.1; needs a non-recursive base case
// the whole pattern, copy-paste ready type ElementType<T> = T extends (infer U)[] ? U : T; type ReturnTypeOf<T> = T extends (...args: any[]) => infer R ? R : never; // distribution, on purpose type ToArray<T> = T extends any ? T[] : never; // string[] | number[] type ToArrayWhole<T> = [T] extends [any] ? T[] : never; // (string | number)[] // recursive, with a base case type DeepAwaited<T> = T extends Promise<infer V> ? DeepAwaited<V> : T; 

Key takeaways

  • A conditional type (T extends U ? X : Y) is a type-level if/else, resolved the moment a concrete type fills in T — or deferred until one does.
  • When the checked type is a naked type parameter, the conditional distributes over a union: it runs once per member and unions the results. Wrap both sides in a tuple ([T] extends [U]) to run it once for the whole union instead.
  • infer captures a type out of a matching shape inside the extends clause; when the same capture appears in several positions, covariant positions union the candidates and contravariant positions intersect them.
  • Exclude, Extract, NonNullable, ReturnType, and Awaited aren't compiler magic — they're ordinary conditional types, some of them recursive, living in TypeScript's own standard library.

That string[] | number[] from the opening isn't a quirk to work around — it's the distribution rule doing exactly what it's defined to do. Once you can see a conditional type as "one question, asked once per union member whenever the checked type is naked," every one of these results stops being a surprise and starts being something you predict before you hit compile.

Has a distributive conditional type ever handed you a union of arrays when you expected one array of a union? Tell me what you were building when it happened.

🧠 Test yourself

Think it clicked? Take the 8-question quiz →

Instant feedback, a hint on every question, and an explanation for each answer — right or wrong.

📚 Read next

🚀 Want more like this? Every guide, playground, and quiz lives on bestpractic.org — open it and sign up free so the next one finds you.

Thanks for reading! Let's stay connected:

原文:https://www.a8q9.cn/en/article/typescript-conditional-types-explained-the-complete-guide-29975d.html

相关文章