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>; // 7All lessons in this course
- Counting with Tuple Length
- Type-Level Addition and Subtraction
- Type-Level Comparisons
- Practical Numeric Type Utilities