Search⌘ K
AI Features

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.

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:

TypeScript 4.9.5
// The type takes in a generic parameter T and checks whether T is of type number or string.
// If T is a number, then NumberOrString<T> is of type number. Otherwise, it's of type string.
type NumberOrString<T> = T extends number ? number : string;
function logNumberOrString<T>(input: NumberOrString<T>) {
console.log(`logNumberOrString : ${input}`);
}
// Calls to the logNumberOrString function with different input types.
logNumberOrString<number>(1);
logNumberOrString<string>("test");
logNumberOrString<boolean>(true);
Conditional type within a function
  • We have ...