0Pricing
TypeScript Academy · Lesson

Type-Level Addition and Subtraction

Build arithmetic operations from tuple manipulation.

Arithmetic by Length

With the tuple-length representation, addition becomes concatenation and subtraction becomes removing a prefix. You compute on tuples, then read the resulting length.

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

Addition

To add A + B: build a tuple of length A, build one of length B, spread both into a new tuple, and read its length.

type Add<A extends number, B extends number> =
  [...BuildTuple<A>, ...BuildTuple<B>]["length"];

type S = Add<3, 4>; // 7

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