Conditional types
Overview
Mapped types loop over keys. Conditional types make decisions: if this type is a string, produce that; otherwise produce something else. Combined with infer, they can pull types out of other types — the element type of an array, the value inside a promise, a function’s parameters. You’ll mostly use conditional types through utilities like ReturnType, but knowing how they work makes library types readable and lets you build your own.
The syntax
type Label<T> = T extends string ? "text" : "other";
type A = Label<"hi">; // "text"
type B = Label<42>; // "other"It reads like the JavaScript ternary: Check extends Test ? IfTrue : IfFalse. Here extends means “is assignable to” — the same question TypeScript asks when you assign a value to a variable.
Conditional types are most useful when the checked type is a type parameter, so the result depends on how the type is used.
infer: pulling types out
Inside the extends clause, infer X declares a new type variable that TypeScript fills in by matching:
type ElementOf<T> = T extends (infer E)[] ? E : never;
type UnwrapPromise<T> = T extends Promise<infer V> ? V : T;
type FirstArg<F> = F extends (first: infer A, ...rest: never[]) => unknown ? A : never;
type X = ElementOf<string[]>; // string
type Y = UnwrapPromise<Promise<User>>; // User
type Z = FirstArg<(id: number) => void>; // number“If T looks like an array of something, call that something E and return it.” This is how the built-ins are written:
type MyReturnType<F> = F extends (...args: never[]) => infer R ? R : never;
type MyParameters<F> = F extends (...args: infer P) => unknown ? P : never;(The real Awaited is more sophisticated — it unwraps nested promises and “thenable” objects.)
Distribution over unions
When a conditional type is applied to a union, it’s applied to each member separately, and the results are joined:
type Label<T> = T extends string ? "text" : "other";
type C = Label<string | number>; // "text" | "other"
// = Label<string> | Label<number>That’s what makes filtering utilities work:
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 Roles = MyExclude<"admin" | "editor" | "guest", "guest">; // "admin" | "editor"Each member that matches becomes never, and never disappears from a union.
If you don’t want distribution, wrap both sides in brackets: [T] extends [string] ? … : … checks the union as a whole.
Combining with mapped types
Conditional types often appear inside mapped types to filter or transform properties:
// Keys of T whose values are functions
type FunctionKeys<T> = {
[K in keyof T]: T[K] extends (...args: never[]) => unknown ? K : never;
}[keyof T];
type Service = { name: string; start(): void; stop(): void };
type Methods = FunctionKeys<Service>; // "start" | "stop"The mapped type produces { name: never; start: "start"; stop: "stop" }; indexing it with [keyof T] collects the values into a union, and the never drops out.
Testing your types
Complex types deserve tests. A common pair of helpers turns type expectations into compile errors:
type Equal<A, B> =
(<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? true : false;
type Expect<T extends true> = T;
type Tests = [
Expect<Equal<ElementOf<string[]>, string>>,
Expect<Equal<UnwrapPromise<Promise<number>>, number>>,
];Equal uses a trick to check that two types are exactly the same (not just assignable to each other). Expect only accepts true, so a wrong result is a compile error:
type Wrong = Expect<Equal<ElementOf<number[]>, string>>;
// error TS2344: Type 'false' does not satisfy the constraint 'true'.Test runners also have type assertions — Vitest’s expectTypeOf (Testing with Vitest).
When to write conditional types
Conditional types are powerful, and it’s easy to get carried away. In application code, you’ll rarely need more than the built-in utilities. They earn their place in:
- library code, where one function must return precisely typed results for many inputs;
- shared utilities in large codebases (typed event systems, API clients, ORMs);
- extracting types from third-party functions that don’t export them.
If a type takes more than a few seconds to understand, add a comment with an example — and a test.
Remember:
A extends B ? X : Yis type-level if/else;infercaptures a piece of a matching type; unions are processed one member at a time.
Type-level helpers with tests
Copy the Equal and Expect helpers from the lesson. Write and test five conditional types: (1) IsString<T> — true or false; (2) ElementOf<T> — the element type of an array type, otherwise never; (3) UnwrapPromise<T> — the value inside a promise, or T unchanged; (4) FunctionKeys<T> — the keys of T whose values are functions; (5) ParamOf<F> — the type of the first parameter of a one-parameter function. Write one Expect<Equal<…>> test per type (use a union for at least one, to see distribution). Prove a failing test is caught with // @ts-expect-error. Print All type tests passed at the end (if it compiles, they passed!).
type Equal<A, B> = (<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? true : false;
type Expect<T extends true> = T;
type Service = { name: string; start(): void; stop(force: boolean): void };
// 1–5 and their teststype Equal<A, B> = (<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? true : false;
type Expect<T extends true> = T;
type Service = { name: string; start(): void; stop(force: boolean): void };
// 1
type IsString<T> = T extends string ? true : false;
// 2
type ElementOf<T> = T extends readonly (infer E)[] ? E : never;
// 3
type UnwrapPromise<T> = T extends Promise<infer V> ? V : T;
// 4
type FunctionKeys<T> = { [K in keyof T]: T[K] extends (...args: never[]) => unknown ? K : never }[keyof T];
// 5
type ParamOf<F> = F extends (arg: infer P) => unknown ? P : never;
type Tests = [
Expect<Equal<IsString<"hi">, true>>,
Expect<Equal<IsString<42>, false>>,
Expect<Equal<IsString<"a" | 1>, boolean>>, // distributes: true | false
Expect<Equal<ElementOf<string[]>, string>>,
Expect<Equal<ElementOf<readonly [1, 2]>, 1 | 2>>,
Expect<Equal<UnwrapPromise<Promise<number>>, number>>,
Expect<Equal<UnwrapPromise<string>, string>>,
Expect<Equal<FunctionKeys<Service>, "start" | "stop">>,
Expect<Equal<ParamOf<(id: number) => void>, number>>,
];
// @ts-expect-error -- a wrong expectation fails to compile
type Failing = Expect<Equal<ElementOf<number[]>, string>>;
console.log("All type tests passed");Summary
T extends U ? X : Ychooses a type: X if T is assignable to U, otherwise Y.infercaptures part of a type inside the condition:T extends Promise<infer V> ? V : T.- Conditional types distribute over unions: each member is checked separately and the results are joined.
- Many utility types are conditional types: Exclude, Extract, NonNullable, ReturnType, Parameters, Awaited.
- Test complex types with
Expect<Equal<Actual, Expected>>so mistakes become compile errors.