Syntax
T extends U ? TrueType : FalseTypeExamples
A Basic Conditional Type
Selecting a type based on whether another type satisfies a condition.
type IsString<T> = T extends string ? "yes" : "no";
type A = IsString<string>; // "yes"
type B = IsString<number>; // "no"
type ExtractArray<T> = T extends (infer U)[] ? U : T;
type C = ExtractArray<number[]>; // number - extracted the element type
type D = ExtractArray<string>; // string - unchanged, T was not an arrayPractical Use: A Custom Utility Type
Building a type that filters out null/undefined, a common real-world pattern.
type NonNullable<T> = T extends null | undefined ? never : T;
type A = NonNullable<string | null>; // string
type B = NonNullable<number | undefined>; // number
// This is actually one of TypeScript's own built-in utility typesBest practices
- Use conditional types when a type needs to adapt its shape based on characteristics of another type, similar to overloaded function behavior at the type level
- Study TypeScript's own built-in utility types (like NonNullable, ReturnType) - many are implemented using conditional types and are excellent learning examples
- Keep conditional types as simple as possible - deeply nested conditional chains become genuinely difficult for anyone (including future you) to read
- Combine conditional types with infer when you need to extract and reuse part of the matched type, not just branch based on it
Runtime & versions
Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
TypeScript Handbook