Conditional types
type IsString<T> = T extends string ? "yes" : "no";
type Wrapped<T> = [T] extends [string] ? "yes" : "no";A naked type parameter distributes over unions. any takes both branches. never distributes to never, but a wrapped never follows the ordinary extends rule.
| Type parameter | Description |
|---|---|
T | The type being tested. If it is a bare type parameter, a union argument is split into members before the check. |
U | The type in the extends clause. The true and false branches are chosen per member when the check is distributive. |
Produces: The chosen branch, a union of branches for a distributed union or for any, or never when a distributive check is applied to never.
Type errors
type error— Assigning a value that is not in the resulting type is a type error, such as "maybe" for a "yes" | "no" result, or "yes" for a never result, or "no" for Wrapped of never.
- Conditional types were added in TypeScript 2.8. These results were measured with TypeScript 5.9.3.
- Exclude and Extract are distributive conditionals in the standard typings. See that page for those aliases; this page does not repeat those examples.
type IsString<T> = T extends string ? "yes" : "no";
const yes: IsString<"a"> = "yes";
const no: IsString<1> = "no";
const split: IsString<"a" | 1> = "yes";
const also: IsString<"a" | 1> = "no";
// @ts-expect-error the distributed result is "yes" | "no", not a single "maybe"
const notOnlyYes: IsString<"a" | 1> = "maybe";
type DistNever = IsString<never>;
// @ts-expect-error distributing over never produces never
const fromNever: DistNever = "yes";
type AnyBranch = any extends string ? "yes" : "no";
const anyYes: AnyBranch = "yes";
const anyNo: AnyBranch = "no";
type Wrapped<T> = [T] extends [string] ? "yes" : "no";
const wrappedUnion: Wrapped<"a" | 1> = "no";
const wrappedNever: Wrapped<never> = "yes";
// @ts-expect-error wrapping disables distribution, and never extends string
const wrappedNeverNo: Wrapped<never> = "no";
console.log(yes, split, wrappedUnion, wrappedNever);Expected output
yes yes no yesRelated: Exclude, Extract, and NonNullable