Conditional Types in TypeScript: Understand extends, infer and Union Distribution

Trace conditional types one branch at a time. Learn to extract API data types, filter union members and decide when an entire union must satisfy a condition.

KnowledgeGate Team

Exam prep & CS education

Updated 2 Dec 20266 min read
Conditional Types in TypeScript: Understand extends, infer and Union Distribution

You want an API result type to depend on its input, but every result keeps becoming a broad union that callers must narrow again. Conditional types let you express that relationship, extract a type from a structure and control how unions behave. These examples change compile-time types, not runtime values. The beginner tutorial covers everyday annotations, interfaces, unions and narrowing; this post focuses on conditional branches, infer and union distribution. For a refresher, start with the TypeScript beginner tutorial.

1. Read T extends U ? X : Y as an assignability test

Read T extends U ? X : Y as: if T is assignable to U, choose X; otherwise choose Y. The official TypeScript Handbook explains this assignability rule, inference within matching types and distribution over unions.

Here, extends does not mean exact equality or only class inheritance. Unlike JavaScript's runtime ternary, this expression selects a type during type checking.

ts
type Reference<T> = T extends number
  ? { id: T }
  : { key: T };
type ById = Reference<42>;       // { id: 42 }
type ByKey = Reference<"kg-7">;  // { key: "kg-7" }
const byId: ById = { id: 42 };
const byKey: ByKey = { key: "kg-7" };

For ById, substitute 42 for T. Since 42 is assignable to number, choose { id: T }, producing { id: 42 }. The literal stays specific.

For ByKey, "kg-7" is not assignable to number. Choose { key: T }, producing { key: "kg-7" }. The alias manufactures no objects; the two const initialisers supply the values.

2. Put the condition inside a generic to provide a fallback

Suppose successful responses contain a payload, while errors do not. An extractor can accept either shape:

ts
type Payload<T> = T extends { payload: unknown }
  ? T["payload"]
  : never;

type SuccessPayload = Payload<{
  payload: { id: 42; name: "Asha" }
}>;
type ErrorPayload = Payload<{ error: "missing" }>;

For SuccessPayload, the required payload property exists. The true branch reads its type, so the result is { id: 42; name: "Asha" }. For ErrorPayload, the property is absent. The condition fails and the result is never.

Now move the requirement into the generic parameter:

ts
type RequiredPayload<T extends { payload: unknown }> =
  T["payload"];

Passing { error: "missing" } to RequiredPayload is a type error: that input violates the constraint. Payload accepts the same input and returns a fallback type instead.

Choose a constraint when callers must supply the property. Choose a conditional when your helper should also handle other shapes. never means no possible value; it is neither undefined nor an exception thrown by this helper.

3. Use infer to capture a type from a matching structure

Use infer when you want to name part of the structure being matched:

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

infer E captures an element type for use in the true branch. The readonly pattern accepts both readonly and mutable arrays.

  • Item<readonly [42, "Asha"]> matches the array pattern. Its element type is 42 | "Asha".

  • Item<string[]> matches with E = string, so the result is string.

  • Item<boolean> has no array match, so the false branch returns boolean unchanged.

This examines declared types; it does not read runtime array contents. Apply the same idea to an API response:

ts
type ResponseData<T> = T extends { data: infer D } ? D : never;
type ApiReply = {
  data: { id: 42; name: "Asha" };
  status: 200;
};
type User = ResponseData<ApiReply>;
// { id: 42; name: "Asha" }
Flow diagram showing an ApiReply data object matched with { data: infer D }, producing D with id 42 and name Asha; an error object yields never.

The data property supplies D; the sibling status property is not included. This extracts from an already declared structure. It does not validate network JSON.

4. Trace distributive conditional types one union member at a time

A conditional with a naked type parameter on the checked side distributes over a union. “Naked” means the checked side is T itself, without a wrapper.

ts
type KeepText<T> = T extends string ? T : never;
type StatusText = KeepText<"paid" | 42 | "pending">;

Expand the calculation one member at a time:

  1. KeepText<"paid"> | KeepText<42> | KeepText<"pending">

  2. "paid" | never | "pending"

  3. "paid" | "pending"

Flow diagram splits the union 'paid' | 42 | 'pending', keeps the two string literals, maps 42 to never, and merges the remaining strings.

Both string literals pass and retain their own types. The number literal fails and contributes never. Since never has no possible values, it adds no members to the resulting union.

This resembles filtering, but no JavaScript filtering runs. A union appearing somewhere in an expression is not sufficient for distribution: check whether the conditional directly tests a naked type parameter. That detail determines whether you trace separate branches or one combined check.

5. Wrap the checked types in tuples to test the whole union

Sometimes every possible member must satisfy the requirement:

ts
type AllText<T> = [T] extends [string] ? true : false;

AllText<"paid" | "pending"> is true: both members fit string. AllText<"paid" | 42> is false: ["paid" | 42] is not assignable to [string], because 42 is not a string. Tuple wrapping makes this a single, undistributed check.

The unwrapped T extends string ? true : false instead distributes over "paid" | 42, producing true | false, displayed as boolean. That loses the single yes-or-no answer about the whole union.

The distinction also changes array types:

ts
type EachArray<T> = T extends unknown ? T[] : never;
type TogetherArray<T> = [T] extends [unknown] ? T[] : never;

For string | number, EachArray produces string[] | number[]: either a string array or a number array. TogetherArray produces (string | number)[]: an array allowing both.

Thus ["Asha", 42] fits only the latter, while [42, 7] fits both. Tuple wrapping selects the intended question; it is not an automatic correction for every union.

6. Avoid common traps and practise interview-style type tracing

Three mistakes become easier to spot when you trace the earlier examples:

  • Expecting runtime branching: section 1's Reference describes an object type. Only actual JavaScript code creates the object.

  • Treating assignability as equality: 42 is not identical to number, but it passes section 1's test because it belongs to that type.

  • Overlooking distribution: section 4's KeepText checks each member; section 5's AllText checks the whole union.

One edge case deserves its own line: KeepText<never> is never. There are no union members to process, so no branch runs for a member. Do not explain this as an ordinary false-branch result.

Try these original interview-style exercises. Give a one-sentence reasoning trace before checking each answer:

Expression

Answer and reasoning

Reference<7>

{ id: 7 }, because 7 is assignable to number and the true branch preserves it.

Item<readonly [1, 2]>

1 | 2, because the readonly tuple matches the array pattern with those two element types.

AllText<"ready" | 0>

false, because the entire union cannot fit string.

The Handbook cited earlier supplies the semantics behind these traces. To explore other programming-language concepts, continue with Programming Languages Survey.

7. Choose the helper that matches your next task

Use a conditional branch to describe an input/output relationship, infer to capture a matched type, and tuple wrapping when the entire union must pass. Before writing a helper, decide whether its question concerns each member or the union together.

Next, try ResponseData<{ error: "missing" }>. There is no matching data property, so the extracted type becomes never.

If you are extending JavaScript practice into broader full-stack development, explore the MERN Stack course as an optional next step.