What is the basic syntax of a conditional type, and how does it resemble a ternary expression?
Short answer
A conditional type has the form `T extends U ? X : Y` — evaluated at the type level, it resolves to X if T is assignable to U, and Y otherwise, mirroring the syntax and logic of a runtime ternary expression but operating purely on types.
Advertisement
AModel answer
A conditional type has the form `T extends U ? X : Y` — evaluated at the type level, it resolves to X if T is assignable to U, and Y otherwise, mirroring the syntax and logic of a runtime ternary expression but operating purely on types.
type IsString<T> = T extends string ? true : false;
type A = IsString<'hello'>; // true
type B = IsString<42>; // falseReal-world example
Building a reusable type-level check to conditionally select a return type based on an input type parameter.
Likely follow-ups
- Can conditional types be nested to express multiple branches, like a chain of else-if?
Related topics