Type-Level Arithmetic
February 9, 20261 min readpart 17/20
Difficulty: Expert. Prerequisites: Recursive types, tuple manipulation, conditional types, infer.
Type-level arithmetic involves performing mathematical operations like addition, subtraction, and comparison entirely within TypeScript's type system using tuple lengths. This enables compile-time validations and range types.
Key concepts
- Representing numbers as tuple lengths
- Addition via tuple concatenation
- Subtraction via tuple destructuring
- Comparison operations at type level
- Range and vector types
Example
type BuildTuple<N, T extends any[] = []> = T['length'] extends N ? T : BuildTuple<N, [...T, 0]>;
// Add
type Add<A extends number, B extends number> = [...BuildTuple<A>, ...BuildTuple<B>]['length'];
type Sum = Add<3, 4>; // 7
// Subtract
type Sub<A extends number, B extends number> =
BuildTuple<A> extends [...BuildTuple<B>, ...infer R] ? R['length'] : never;
type Diff = Sub<10, 3>; // 7
// Less than
type LT<A extends number, B extends number> =
BuildTuple<A> extends [...BuildTuple<B>, ...any[]] ? false : true;
type Less = LT<3, 5>; // true
// Range (0 to N-1)
type Range<N, A extends number[] = []> = A['length'] extends N ? A[number] : Range<N, [...A, A['length']]>;
type R5 = Range<5>; // 0 | 1 | 2 | 3 | 4
// Fixed-length vector
type Vec<N extends number> = BuildTuple<N, number[]> & number[];
type Vec3 = Vec<3>; // [number, number, number]
const v: Vec3 = [1, 2, 3]; // OK
// Used in: ts-arithmetic, HotScript — same tuple-length encoding for compile-time mathResources
- Type Challenges: Arithmetic challenges
- HotScript: Type-level ops library
Practice
- Integer to Positive (TypeHero, Hard)
- Absolute (TypeHero, Medium)
- Percentage Parser (TypeHero, Medium)
- Greater Than (Type Challenges, Medium)
- MinusOne (Type Challenges, Medium)
- Absolute (Type Challenges, Medium)
- Two Sum (Type Challenges, Hard)
- Sum (Extreme) (Type Challenges, Extreme)
- Multiply (Extreme) (Type Challenges, Extreme)
Hints
- Build a tuple of a specific length, then use its .length property to get the number type.
- Addition = concatenate two tuples and take the length; subtraction = destructure and take remainder length.