Conditional Types and Chaining

Learn about TypeScript's conditional types for dynamic type definition in functions and how to use conditional type chaining to obtain specific types.

Conditional types in functions

We should be familiar with the concept of conditional expressions with the following format:

(conditional) ? ( true statement ) : ( false statement );

Here, we have a condition followed by a question mark (?) and then either a true expression or a false expression, separated by a colon (:).

We can use this syntax with types as well to form what is known as a conditional type:

type NumberOrString<T> = T extends number ? number : string;

Here, we have defined a type named NumberOrString that uses the generic syntax to define a type named T. The type of T is set to the result of the conditional type statement to the right of the assignment operator (=).

This conditional type statement checks whether the type of T extends the type number. If it does, it will return the number type, and if not, it will return the string type.

We can use this conditional type within a function as follows:

Get hands-on with 1200+ tech skills courses.