Thuta Learning
TypeScript
AdvancedProgrammingIntermediate

Conditional Types & infer

TypeScriptLesson 2135 min

What you'll walk away with

  • Read a T extends U ? X : Y conditional type and predict which branch it picks
  • Extract a promise's value, an array's item and a function's parameter type with infer
  • Know when a conditional type distributes over a union, and turn it off with [T]
  • Reach for Awaited, ReturnType, Parameters, Exclude and NonNullable before writing your own

Explain it simply

Conditional types and infer in plain language

A conditional type is an if/else that runs on types instead of values. It says 'if this type is a Promise, give me one thing, otherwise give me another'. infer is the grabbing tool that comes with it: 'and if it is a Promise, tell me what is inside'.

It is like unpacking a parcel. Promise<User> is a box with a User inside. The conditional type checks whether it is a box, and infer hands you the item, so you get User without writing it again by hand. All of this happens at compile time; nothing of it reaches the running code.

Problem → Why → Solution

The problem: you need the type inside a wrapper

You have an async function getProfile() and want the type of the data it resolves to, so a React component can accept it as a prop. Writing that type by hand duplicates the function's shape and drifts as soon as the function changes. ReturnType<typeof getProfile> gives Promise<Profile>, which is the wrapper, not the data. You need a way to look inside a type and pull a piece out.

profile-card.ts
async function getProfile() {
  return { name: "Ada", followers: 1200 };
}

// Hand-copied: drifts when getProfile changes
type Profile = { name: string; followers: number };

type Wrong = ReturnType<typeof getProfile>; // Promise<...>, not the data
function profileTitle(profile: Wrong) {
  return profile.name; // error: 'name' does not exist on type 'Promise<...>'
}

Why this is hard without new tools

Promise<T>, T[] and function types wrap the type you actually care about. Without a way to match a pattern and extract the inner part, you end up duplicating types by hand. Conditional types with infer are that pattern match, and they are how ReturnType, Parameters and Awaited are built.

Core concept: if/else and pattern matching on types

A conditional type has the shape T extends U ? X : Y. If T is assignable to U, the result is X; otherwise it is Y. extends here means 'fits into', exactly as in a generic constraint: string extends string | number is true, and { id: string; name: string } extends { id: string } is true too, because extra properties are allowed. Conditional types are almost always written with a type parameter, so the decision is made fresh for each type you plug in.

infer lets you capture a piece of the type you are matching against. In T extends Promise<infer Value> ? Value : T, TypeScript tries to see T as a Promise of something; if it succeeds, it binds that something to Value, which you can use in the true branch only. infer works anywhere inside the pattern: the element of an array ((infer Item)[]), a function's return type ((...args: any[]) => infer R), or its parameters.

When the checked type is a naked type parameter and you pass a union, the condition is applied to each member separately and the results are joined. This is called distribution. type ToArray<T> = T extends unknown ? T[] : never turns string | number into string[] | number[], not (string | number)[]. Distribution is how Exclude<T, U> removes members from a union. To switch it off, wrap both sides in a tuple: [T] extends [U].

Built-inWhat it does
NonNullable<T>removes null and undefined
Exclude<T, U> / Extract<T, U>drops / keeps members assignable to U
ReturnType<F> / Parameters<F>a function's return type / parameter tuple
Awaited<T>a promise's resolved value, unwrapped recursively

Most of the time you use these built-ins rather than writing your own. Awaited<T>, built in since TypeScript 4.5, is the production-grade version of this lesson's AwaitedResult: it also unwraps nested promises and other thenables. Remember that all of this is compile-time only; a conditional type cannot inspect a value at runtime, so it never replaces a real check such as typeof or a schema.

Think of it as a pattern match on types
  1. Ask: does T fit the pattern?
  2. infer names the part you need
  3. Yes: return the true branch
  4. No: return the fallback

With a union, the question is asked once per member, then the answers are joined.

General pattern

typescript
type Check<T> = T extends Pattern ? WhenYes : WhenNo;

type Unwrap<T> = T extends Wrapper<infer Inner> ? Inner : T;

type ResultOf<F> = F extends (...args: any[]) => infer R ? R : never;

type NoDistribute<T> = [T] extends [Pattern] ? WhenYes : WhenNo;

The condition tests assignability. infer names a slot inside the pattern for use in the true branch. Wrap T in [T] when a union should be checked as a whole.

Worked example: unwrapping a Promise

AwaitedResult<T> returns the value type inside a Promise, or T unchanged when it is not a Promise. Combined with ReturnType, it derives the Task type from an async function instead of writing it a second time.

conditional-infer.ts
type AwaitedResult<T> = T extends Promise<infer Value> ? Value : T;

type ApiResult = AwaitedResult<Promise<{ id: string }>>; // { id: string }
type PlainResult = AwaitedResult<number>; // number (not a Promise)

async function fetchTask() {
  return { id: "task-1", done: false };
}

// Derive the resolved type from the function instead of writing it again
type Task = AwaitedResult<ReturnType<typeof fetchTask>>;

async function main() {
  const task: Task = await fetchTask();
  const item: ApiResult = { id: task.id };
  const count: PlainResult = 3;
  console.log(item.id, task.done, count);
}

main();

Code breakdown

  1. The conditiontype AwaitedResult<T> = T extends Promise<infer Value> ? Value : T;

    Tries to match T as Promise<something>. On a match it captures something as Value and returns it; otherwise it returns T itself.

  2. Promise branchtype ApiResult = AwaitedResult<Promise<{ id: string }>>; // { id: string }

    Promise<{ id: string }> fits the pattern, so Value becomes { id: string }.

  3. Fallback branchtype PlainResult = AwaitedResult<number>; // number (not a Promise)

    number is not a Promise, so the false branch returns T, which is number, unchanged.

  4. Derive from a functiontype Task = AwaitedResult<ReturnType<typeof fetchTask>>;

    typeof fetchTask takes the function's type, ReturnType extracts Promise<{ id; done }>, and AwaitedResult opens the box. Add a field to fetchTask and Task follows automatically.

You should see
task-1 false 3

Distribution over unions

The two types below differ only in that the second wraps T in a tuple. Compare the results and the commented-out error.

distribution.ts
type ToArray<T> = T extends unknown ? T[] : never;
type ToArrayAll<T> = [T] extends [unknown] ? T[] : never;

type A = ToArray<string | number>; // string[] | number[]
type B = ToArrayAll<string | number>; // (string | number)[]

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

const a: A = ["x", "y"]; // fine: a string[]
// const bad: A = ["x", 1]; // error: a mixed array is neither member
const b: B = ["x", 1]; // fine: one mixed array
const settled: Settled[] = ["success", "error"];
console.log(a, b, settled);

Distribution is usually what you want when filtering unions, as Exclude shows. It surprises people when they write a check such as IsString<T> and pass a union: the answer comes back as "yes" | "no", because each member was checked separately.

In real projects

Conditional types in real projects

You rarely write deep conditional types in application code, but you use them constantly through the standard library and frameworks:

  • Deriving types from functions: Awaited<ReturnType<typeof loadDashboard>> gives a component the exact data shape without duplicating it, and Parameters<typeof sendEmail>[0] reuses a function's options object.
  • Cleaning unions: NonNullable<User | null> after a guard, or Exclude<AppEvent, { type: "internal" }> to hide events from a public API.
  • Library types: some typed routers parse route strings such as "/users/:id" with conditional types and infer, giving you a typed params.id.
  • Keeping helpers honest: a typed wrapper like withRetry<F extends (...args: any[]) => Promise<unknown>>(fn: F) can return a function with the same Parameters<F> and ReturnType<F>, so callers see the original signature.

Common mistakes

Common mistakes with conditional types

Forgetting that a union distributes

IsString<string | number> is "yes" | "no", not "no". If you meant 'is the whole type a string?', wrap both sides: [T] extends [string].

Expecting a runtime effect

A conditional type cannot look at a value; a type IsEmail<T> will never validate an email. Types are erased before the code runs, so pair them with real checks (typeof, a type guard or a schema) at the boundaries.

Building unreadable type puzzles

Deeply nested conditional types produce error messages nobody can read and slow the compiler down. Prefer the built-ins (Awaited, ReturnType, Parameters), give intermediate steps names, and stop when a plain interface would be clearer.

Best practices

Best practices

  • Before writing a type again, ask whether it can be derived from an existing function or value with typeof and the built-ins.
  • Test every conditional type you write with edge inputs such as a union, never and any; distribution can change the result in surprising ways.
  • Document a complex type with a one-line usage example in a comment, so the next reader does not have to hover to understand it.

Mini challenge

Mini challenge: ElementType and FirstParam

Write two extractor types and use them to keep a small event system in sync with its handler function. ElementType<T> gives the item type of an array, or T itself when it is not an array. FirstParam<F> gives the type of a function's first parameter.

  • ElementType<T> uses infer on an array pattern and falls back to T
  • FirstParam<F> uses infer on a function pattern and falls back to never
  • Type the payload of dispatch with FirstParam<typeof onSignup> instead of rewriting it
  • Print one message per queued event
extractors.ts
// TODO: the item type of an array, or T itself
type ElementType<T> = unknown;

// TODO: the type of a function's first parameter, or never
type FirstParam<F> = unknown;

function onSignup(event: { email: string; plan: "free" | "pro" }) {
  return `Welcome ${event.email} (${event.plan})`;
}

// TODO: type payload with FirstParam<typeof onSignup>
function dispatch(payload) {
  // TODO: hand the payload to onSignup and return its message
}

// TODO: build a queue of events, add one more typed as ElementType<typeof queue>,
// and print dispatch(event) for each of them

Expected: One line per event, such as Welcome ada@example.com (pro). A payload with plan: "gold" does not compile, because FirstParam picked up onSignup's exact parameter type.

Show hint

The array pattern is T extends readonly (infer Item)[] ? Item : T. For the function, match against (first: infer P, ...rest: any[]) => any.

Show solution
extractors.ts
type ElementType<T> = T extends readonly (infer Item)[] ? Item : T;
type FirstParam<F> = F extends (first: infer P, ...rest: any[]) => any ? P : never;

function onSignup(event: { email: string; plan: "free" | "pro" }) {
  return `Welcome ${event.email} (${event.plan})`;
}

type SignupEvent = FirstParam<typeof onSignup>; // { email: string; plan: ... }

function dispatch(payload: SignupEvent): string {
  return onSignup(payload);
}

const queue: SignupEvent[] = [
  { email: "ada@example.com", plan: "pro" },
  { email: "lin@example.com", plan: "free" },
];
type QueueItem = ElementType<typeof queue>; // SignupEvent
const late: QueueItem = { email: "grace@example.com", plan: "free" };

for (const event of [...queue, late]) console.log(dispatch(event));
// dispatch({ email: "x@example.com", plan: "gold" }); // error: not a valid plan

Quick quiz 1 / 3

Given type ElementType<T> = T extends (infer U)[] ? U : never, what is ElementType<number>?

Quick quiz 2 / 3

Given type IsString<T> = T extends string ? "yes" : "no", what is IsString<string | number>?

Quick quiz 3 / 3

Given async function loadUser(): Promise<User>, which type gives you User?

What to remember

  • T extends U ? X : Y is if/else for types: X when T fits into U, otherwise Y.
  • infer captures a piece of the matched pattern for use in the true branch.
  • A condition on a naked type parameter distributes over union members; wrap it in [T] to stop that.
  • Use Awaited, ReturnType, Parameters, Exclude and NonNullable before writing your own; none replaces a runtime check.

Conditional Types — TypeScript

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.