Conditional Types

What

Conditional types allow you to define a type that changes based on a condition, similar to a ternary expression in JavaScript. The basic syntax is T extends U ? X : Y.

How

You use the extends keyword to check if a type satisfies a certain constraint:

type IsString<T> = T extends string ? true : false;

type A = IsString<"hello">; // true
type B = IsString<42>;      // false

Why

Conditional types are the foundation for building advanced, dynamic type transformations. They are particularly useful for filtering unions or creating utility types that behave differently depending on the input. For example, you can use them to extract only the “mouse-related” events from a large union of event types based on the presence of x and y coordinates.

Summary

Conditional types bring logic to your type definitions, allowing for highly flexible and dynamic type systems.