TypeScript Conditional Types & infer
A conditional type chooses between two types based on a test, in the same way the ? : operator chooses between two values:
type Result = SomeType extends OtherType ? TrueType : FalseType;Read A extends B as "is A assignable to B?". Conditional types are mostly useful inside generics, where the input type isn't known until the type is used. Together with the infer keyword they let you compute types — extracting the element type of an array, the return type of a function, or the value inside a Promise.
A first example
type IsString<T> = T extends string ? "yes" : "no";
type A = IsString<"hello">; // "yes"
type B = IsString<42>; // "no"
const a: A = "yes";
const b: B = "no";
console.log(a, b);
type Label<T> = T extends number ? `#${T}` : T extends boolean ? "flag" : "text";
const l1: Label<7> = "#7";
const l2: Label<true> = "flag";
const l3: Label<"x"> = "text";
console.log(l1, l2, l3);yes no
#7 flag text
Conditional types can be chained, like else if, as Label shows.
Distribution over unions
When the checked type is a bare type parameter and you pass a union, the conditional is applied to each member separately and the results are joined back into a union. This is called a distributive conditional type:
type NonNull<T> = T extends null | undefined ? never : T;
type Clean = NonNull<string | null | number | undefined>;
// = NonNull<string> | NonNull<null> | NonNull<number> | NonNull<undefined>
// = string | never | number | never
// = string | number
const values: Clean[] = ["a", 1, "b"];
console.log(values);
type ToArray<T> = T extends unknown ? T[] : never;
type Arrs = ToArray<string | number>; // string[] | number[]
const arr: Arrs = [1, 2, 3];
console.log(arr);[ 'a', 1, 'b' ]
[ 1, 2, 3 ]
Since never disappears from unions, returning never is how you filter members out. That's exactly how the built-ins Exclude, Extract and NonNullable work.
Note: If you don't want distribution, wrap both sides in brackets:
[T] extends [string] ? ... : ....
Extracting types with infer
Inside the extends clause you can write infer X to declare a new type variable that TypeScript fills in by pattern matching. It's only available in the true branch:
type ElementOf<T> = T extends (infer E)[] ? E : never;
type Unwrap<T> = T extends Promise<infer V> ? V : T;
type FirstArg<F> = F extends (first: infer A, ...rest: any[]) => any ? A : never;
type E = ElementOf<string[]>; // string
type V = Unwrap<Promise<number>>; // number
type F = FirstArg<(id: boolean, n: number) => void>; // boolean
const e: E = "item";
const v: V = 10;
const f: F = true;
console.log(e, v, f);item 10 true
Built-in conditional types
The standard library ships with many conditional types that you can use directly:
| Utility | Result |
|---|---|
Exclude<T, U> |
members of T not assignable to U |
Extract<T, U> |
members of T assignable to U |
NonNullable<T> |
T without null and undefined |
ReturnType<F> |
return type of function type F |
Parameters<F> |
parameter types of F as a tuple |
Awaited<T> |
the value inside (possibly nested) promises |
InstanceType<C> |
the instance type of a class constructor |
They're extremely handy for deriving types from existing code instead of writing them twice:
function createUser(username: string, age: number) {
return { username, age, createdAt: "2024-01-01" };
}
type User = ReturnType<typeof createUser>;
type Args = Parameters<typeof createUser>; // [username: string, age: number]
const args: Args = ["lan", 31];
const user: User = createUser(...args);
console.log(user);
type Status = "draft" | "published" | "archived";
type Visible = Exclude<Status, "archived">; // "draft" | "published"
const s: Visible = "archived";main.ts(14,7): error TS2322: Type '"archived"' is not assignable to type 'Visible'.
The error shows that Visible really excludes "archived". Remove that last line and the rest runs fine.
A recursive example
Conditional types may refer to themselves, which lets you unwrap nested structures — here, flattening arrays of any depth:
type Flatten<T> = T extends readonly (infer Inner)[] ? Flatten<Inner> : T;
type Deep = Flatten<number[][][]>; // number
function flatten<T>(input: T[]): Flatten<T>[] {
return (input as unknown[]).flat(Infinity) as Flatten<T>[];
}
const nested = [[1, [2, 3]], [4], [[5]]];
const flat: Deep[] = flatten(nested);
console.log(flat);[ 1, 2, 3, 4, 5 ]
Tip: Conditional types are powerful but can become hard to read. Use them in reusable helpers with clear names, and prefer simple types in everyday application code.
Test yourself
What is Exclude<"a" | "b" | "c", "a">?
- "a"
- "b" | "c"
- "a" | "b" | "c"
- never
Where can a type variable declared with infer be used?
- Anywhere in the file
- Only in the true branch of that conditional type
- Only in the false branch
- Only in function bodies
What is ReturnType<() => Promise<string>>?
- string
- Promise<string>
- () => string
- unknown