Conditional Types and Chaining
Explore how to use conditional types in TypeScript to create types that depend on other types, and understand how chaining these conditions can model complex type relationships. This lesson guides you through defining conditional types with generics, applying them in functions, and chaining conditions to return specific tuple types based on interface checks.
We'll cover the following...
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:
-
We have ...