Nested conditional types let you make decisions inside other decisions in TypeScript. This helps create smart types that change based on many conditions.
Nested conditional types in Typescript
type Result<T> = T extends string ? (T extends 'hello' ? number : boolean) : null;
Nested conditional types use a conditional inside another conditional's true or false branch.
They read like: if T is string, then check if T is 'hello', else boolean; otherwise null.
type Check<T> = T extends number ? (T extends 1 ? 'One' : 'Other number') : 'Not a number';
type Nested<T> = T extends string ? (T extends 'yes' ? true : false) : undefined;
type DeepCheck<T> = T extends object ? (keyof T extends never ? 'Empty object' : 'Has keys') : 'Not object';
This program defines a nested conditional type Describe that checks the type T in steps. It returns different strings based on T's value or type. Then it assigns variables with these types and prints their values.
type Describe<T> = T extends string ? (T extends 'hello' ? 'Greeting' : 'Other string') : T extends number ? (T extends 0 ? 'Zero' : 'Non-zero number') : 'Unknown'; // Test cases let a: Describe<'hello'> = 'Greeting'; let b: Describe<'world'> = 'Other string'; let c: Describe<0> = 'Zero'; let d: Describe<42> = 'Non-zero number'; let e: Describe<boolean> = 'Unknown'; console.log(a); console.log(b); console.log(c); console.log(d); console.log(e);
Nested conditional types can get complex, so keep them readable by formatting well.
They help create very flexible and precise types in TypeScript.
Use them when simple conditional types are not enough.
Nested conditional types let you put one condition inside another.
They help create types that depend on multiple checks.
Use them to make your types smarter and more flexible.