Conditional types in TypeScript allow you to create types that depend on a condition. They are used to select one type based on whether a condition is met. The syntax looks like this:
T extends U ? X : Y
Where T
is the type being checked, U
is the type to compare against, X
is the type returned if the condition is met, and Y
is the type returned if the condition is not met.
Example:
type IsString<T> = T extends string ? 'Yes' : 'No'; type Test1 = IsString<'hello'>; // 'Yes' type Test2 = IsString<42>; // 'No'
In this example, if type T
is a string
, it will return 'Yes'
, otherwise, it will return 'No'
. Conditional types are useful when you want to adjust types based on other types.