What Are Conditional Types?
You'll learn: How TypeScript lets you choose between types based on conditions, using syntax that looks like JavaScript's ternary operator.
The Core Idea
Conditional types allow TypeScript to select one type or another based on whether a type satisfies a condition. Think of them as an if-else statement for types themselves.
The syntax mirrors JavaScript's ternary operator:
T extends U ? X : Y
This reads as: "If type T extends (is assignable to) type U, then use type X, otherwise use type Y."
A Simple Example
type IsString<T> = T extends string ? "yes" : "no";
type A = IsString<string>; // type A = "yes"
type B = IsString<number>; // type B = "no"
Here, IsString checks if the type parameter T is assignable to string. If yes, it resolves to the literal type "yes", otherwise "no".
Why This Matters
Conditional types enable type-level logic. They let you create types that adapt based on their inputs, making your generic types more intelligent and precise. Just as JavaScript's ternary operator lets you choose values at runtime, conditional types let TypeScript choose types at compile time.
This becomes the foundation for many advanced TypeScript patterns you'll encounter in real-world code, from filtering object properties to extracting function return types.
Key Takeaway: Conditional types use T extends U ? X : Y syntax to select between types based on assignability checks, bringing if-else logic to TypeScript's type system.