Conditional Types
Writing 'if' statements for your types.
The Type-Level Ternary
Conditional types allow you to create types that choose one of two possible outputs based on a condition.
They use the exact same ternary syntax as JavaScript (condition ? true_branch : false_branch), but instead of checking runtime values, they check type assignability.
Dynamic Type Utilities
Without conditional types, you have to write a separate type for every possible scenario.
With conditional types, you can write highly dynamic, reusable utility types that automatically adjust their shape based on the type variable passed into them.
Syntax
typescript
// If T is a string, return 'yes', otherwise return 'no'.
type IsString<T> = T extends string ? "yes" : "no";
type A = IsString<"hello">; // "yes"
type B = IsString<42>; // "no"
// A more realistic example:
// If T is an array, extract its element type. Otherwise, leave it alone.
type Flatten<T> = T extends any[] ? T[number] : T;
type C = Flatten<string[]>; // string
type D = Flatten<number>; // number
Try it
Pass different types into the IsString<T> conditional type evaluator and watch how the ternary logic resolves to the true or false branch.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Conditional types use the syntax
T extends U ? X : Y. - The condition
T extends Uchecks ifTis assignable toU. - When given a union type, conditional types distribute across the union automatically.
- They are the foundation of advanced TypeScript utility types.
Done with this concept?
Mark it complete to track your progress. No login needed.