0
0
Typescriptprogramming~7 mins

Nested conditional types in Typescript

Choose your learning style9 modes available
Introduction

Nested conditional types let you make decisions inside other decisions in TypeScript. This helps create smart types that change based on many conditions.

When you want a type to change based on multiple checks.
When you need to handle complex type logic in reusable ways.
When you want to create types that depend on other types deeply.
When you want to avoid repeating similar conditional checks.
When building libraries that need flexible type behavior.
Syntax
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.

Examples
This type checks if T is a number. If yes, it checks if T is exactly 1. If yes, it returns 'One', else 'Other number'. If T is not a number, it returns 'Not a number'.
Typescript
type Check<T> = T extends number ? (T extends 1 ? 'One' : 'Other number') : 'Not a number';
This type returns true if T is the string 'yes', false if T is any other string, and undefined if T is not a string.
Typescript
type Nested<T> = T extends string ? (T extends 'yes' ? true : false) : undefined;
This type checks if T is an object. If yes, it checks if it has keys. If no keys, returns 'Empty object', else 'Has keys'. If not an object, returns 'Not object'.
Typescript
type DeepCheck<T> = T extends object ? (keyof T extends never ? 'Empty object' : 'Has keys') : 'Not object';
Sample Program

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.

Typescript
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);
OutputSuccess
Important Notes

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.

Summary

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.