TypeScript ยท Chapter 37 of 44

TypeScript Conditional Types

Conditional types let you choose between two types based on a condition, similar to a ternary expression but evaluated at the type level. The syntax is `T extends U ? X : Y`.

Conditional types are especially powerful when combined with generics, letting a type change its shape depending on what type is passed in, enabling very flexible and precise type definitions.

Syntax
type IsString<T> = T extends string ? "yes" : "no";

Basic conditional types

Writing `type IsString<T> = T extends string ? "yes" : "no";` checks whether T extends (is compatible with) string, resolving to one of two literal types.

Conditional types with generics

Conditional types are often used inside generic type aliases or utility types to adapt behavior based on the actual type supplied by the caller.

Example 1 (typescript)
type IsString<T> = T extends string ? "yes" : "no";
type A = IsString<string>;
type B = IsString<number>;
const a: A = "yes";
const b: B = "no";
console.log(a, b);
Output
yes no

A resolves to the "yes" branch and B resolves to the "no" branch based on the conditional check.

Example 2 (typescript)
type ElementType<T> = T extends (infer U)[] ? U : T;
type Num = ElementType<number[]>;
const n: Num = 5;
console.log(n);
Output
5

The conditional type uses `infer` to extract the element type out of an array type.

Key points

  • Conditional types use the syntax `T extends U ? X : Y`.
  • They let a type resolve differently depending on another type.
  • The `infer` keyword can extract a type from within a conditional check.
  • Conditional types are commonly combined with generics for flexible utilities.
๐Ÿ’ก Note: Conditional types are an advanced feature; you'll use them more when building custom utility types.

๐Ÿ“ Quick Quiz

1. What is the syntax for a conditional type?

2. What does the `infer` keyword do?

3. Conditional types are most often combined with: