TypeScript
/Advanced
Conditional Types
Definition
Types that select one of two possible types based on a condition expressed as a type relationship test (`T extends U ? X : Y`).
Explain Like I'm New
It's literally an `if / else` statement, but for the Type System. It says: 'If the type passed in is a String, output a Boolean type. Otherwise, output a Number type.'
Real World Example
Creating an API fetcher type that checks: 'If the user asked for a `User`, return `UserResponse`. If they asked for a `Post`, return `PostResponse`.'
Common Use Cases
- •Advanced generic APIs
- •Extracting/Excluding specific types from Unions
Terminal Output
bash / terminal
// A basic conditional type
// If T is a string, become 'true'. Else, become 'false'.
type IsString<T> = T extends string ? true : false;
type A = IsString<"Hello">; // true
type B = IsString<123>; // false
// A real-world Distributive Conditional Type
// Removes all 'null' or 'undefined' from a union type
type NonNullableCustom<T> = T extends null | undefined ? never : T;
type ValidData = NonNullableCustom<string | null | number>;
// Distributes to:
// (string extends null? no -> string)
// (null extends null? yes -> never)
// (number extends null? no -> number)
// Final Result: string | number
Interview Questions
basic
- What operator is used to test the condition?
intermediate
- What is a Distributive Conditional Type?
advanced
- How do conditional types power the built-in `Exclude` utility?