0Pricing
TypeScript Academy · Lesson

Practical Numeric Type Utilities

Apply type arithmetic to range and length constraints.

From Theory to Tools

Arithmetic and comparison become useful when packaged as practical utilities: ranges, length-enforced arrays, clamped indices. This lesson turns the primitives into things you would actually ship.

type BuildTuple<N extends number, Acc extends unknown[] = []> =
  Acc["length"] extends N ? Acc : BuildTuple<N, [...Acc, unknown]>;

Enumerate: 0 to N-1

A foundational helper produces a union of all numbers from 0 to N-1. Build a tuple of length N and read every key index.

type Enumerate<N extends number, Acc extends number[] = []> =
  Acc["length"] extends N
    ? Acc[number]
    : Enumerate<N, [...Acc, Acc["length"]]>;

type A = Enumerate<4>; // 0 | 1 | 2 | 3

All lessons in this course

  1. Counting with Tuple Length
  2. Type-Level Addition and Subtraction
  3. Type-Level Comparisons
  4. Practical Numeric Type Utilities
← Back to TypeScript Academy