Skip to content

Type-level arithmetic and recursion limits

Relay retries a job up to maxAttempts times, and the policy is written as a literal: maxAttempts: 3. The log line printed attempt 4 of 3, because attempt is a number and the loop was off by one. The type system knew the limit and could not use it. If attempt had the type 1 | 2 | 3, the off-by-one would not compile.

TypeScript has no arithmetic on types. 3 + 1 is not a type. It has one counting tool: the length of a tuple is a number literal, and tuples can be built and taken apart. This lesson builds Add, Subtract, LessThan and Range on that, then measures where the compiler stops, which is the part that decides whether the code is usable.

A tuple [unknown, unknown, unknown] has length: 3. To get the number 3 as a type, build a tuple of three elements and read its length. Tuple<T, N> builds it by adding one element per step until the length matches:

type Tuple<T, N extends number, Acc extends T[] = []> = Acc["length"] extends N
? Acc
: Tuple<T, N, [...Acc, T]>
type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false
type Expect<T extends true> = T
export type Three = Expect<Equal<Tuple<"x", 3>, ["x", "x", "x"]>>
export type Length = Expect<Equal<Tuple<unknown, 3>["length"], 3>>

Acc is an accumulator: the tuple built so far. The recursion stops when its length equals N. One trap: if N is the wide type number, Acc["length"] extends number is true at once and the result is [], which is wrong. Guard the wide case first:

type Tuple<T, N extends number, Acc extends T[] = []> = number extends N
? T[]
: Acc["length"] extends N
? Acc
: Tuple<T, N, [...Acc, T]>
type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false
type Expect<T extends true> = T
export type Wide = Expect<Equal<Tuple<string, number>, string[]>>

With Tuple, arithmetic is tuple surgery. Addition spreads two tuples into one and reads the length. Subtraction asks whether the first tuple starts with the second, and the leftover is the answer:

type Tuple<T, N extends number, Acc extends T[] = []> = number extends N
? T[]
: Acc["length"] extends N
? Acc
: Tuple<T, N, [...Acc, T]>
type Add<A extends number, B extends number> = [...Tuple<unknown, A>, ...Tuple<unknown, B>]["length"]
type Subtract<A extends number, B extends number> = Tuple<unknown, A> extends [...Tuple<unknown, B>, ...infer Rest]
? Rest["length"]
: never
type LessThan<A extends number, B extends number> = Tuple<unknown, A> extends [...Tuple<unknown, B>, ...unknown[]]
? false
: true
type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false
type Expect<T extends true> = T
export type Sum = Expect<Equal<Add<400, 300>, 700>>
export type Difference = Expect<Equal<Subtract<500, 123>, 377>>
export type Negative = Expect<Equal<Subtract<3, 5>, never>>
export type Less = Expect<Equal<LessThan<2, 3>, true>>
export type NotLessWhenEqual = Expect<Equal<LessThan<3, 3>, false>>

Subtract<3, 5> is never: three elements cannot start with five. Types have no negative lengths, so a subtraction that goes below zero has no answer. LessThan<A, B> is “A does not start with B”: if A has at least B elements, A is not smaller. These three are not recursive on their own. All the recursion is inside Tuple.

Range<From, To> is the union of the integers from From to To, both included. Walk a tuple up from From and collect each length into a union. A guard returns never when the range runs backwards, because the walk would never meet To:

type Tuple<T, N extends number, Acc extends T[] = []> = number extends N
? T[]
: Acc["length"] extends N
? Acc
: Tuple<T, N, [...Acc, T]>
type LessThan<A extends number, B extends number> = Tuple<unknown, A> extends [...Tuple<unknown, B>, ...unknown[]]
? false
: true
type RangeLoop<
From extends number,
To extends number,
Cur extends unknown[] = Tuple<unknown, From>,
Out extends number = never,
> = Cur["length"] extends To ? Out | To : RangeLoop<From, To, [...Cur, unknown], Out | Cur["length"]>
type Range<From extends number, To extends number> = LessThan<To, From> extends true ? never : RangeLoop<From, To>
type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false
type Expect<T extends true> = T
export type Attempts = Expect<Equal<Range<1, 3>, 1 | 2 | 3>>
export type Backwards = Expect<Equal<Range<5, 2>, never>>
type Step<N extends number> = { readonly attempt: Range<1, N>; readonly delayMs: number }
declare function logAttempt(attempt: Range<1, 3>): void
declare function schedule<N extends number>(maxAttempts: N, baseDelayMs: number): Tuple<Step<N>, N>
logAttempt(3)
// @ts-expect-error: attempt 4 of 3 does not compile
logAttempt(4)
const plan = schedule(3, 100)
const last = plan[2]
// @ts-expect-error: a three-attempt plan has no fourth step
plan[3]
console.log(last.attempt)

This is the Relay use. schedule(3, 100) returns a tuple of exactly three steps, each with attempt: 1 | 2 | 3. Reading plan[3] is a type error, so the off-by-one is caught where it is written.

The compiler caps how deep type instantiation can go, and the cap depends on the shape of the recursion. Two versions of Tuple show it. The naive one builds its result as the recursion unwinds, so each step is nested inside the previous one. The accumulator version above puts the recursive call at the very end of the branch, a tail position, and since TypeScript 4.5 the compiler evaluates such a call in a loop:

type NaiveTuple<T, N extends number, Acc extends T[] = []> = Acc["length"] extends N
? []
: [T, ...NaiveTuple<T, N, [...Acc, T]>]
type Tuple<T, N extends number, Acc extends T[] = []> = Acc["length"] extends N ? Acc : Tuple<T, N, [...Acc, T]>
const naiveOk: NaiveTuple<"a", 40>["length"] = 40
// @ts-expect-error: Type instantiation is excessively deep and possibly infinite
const naiveTooDeep: NaiveTuple<"b", 60>["length"] = 60
const tailOk: Tuple<"a", 999>["length"] = 999
// @ts-expect-error: Type instantiation is excessively deep and possibly infinite
const tailTooDeep: Tuple<"b", 1000>["length"] = 1000

Measured on TypeScript 7.0.2 and 5.9.3, with these exact definitions: the naive form compiled at 47 and failed from 50 on (48 and 49 are borderline and depend on where the type is used), and the tail form compiled at 999 and failed at 1000. Both compilers gave the same answers. Treat these as “about 50” and “about 1000”, not as constants: the first depends on how many instantiations each step costs, and the compiler owns the number.

Tail position has rules. The recursive call must be the whole result of a branch of a conditional type. Wrap it in a tuple, an object, a union or an indexed access, and it is nested again. State must travel in a parameter (Acc), not in the result.

A thousand is the ceiling for one-element-at-a-time recursion. To go further, take bigger steps. Instead of counting to 1500, read the digits of "1500": each digit multiplies the tuple by ten (ten copies spread together) and adds the digit. Four steps, not 1500:

type Tuple<T, N extends number, Acc extends T[] = []> = Acc["length"] extends N ? Acc : Tuple<T, N, [...Acc, T]>
type Times10<T extends unknown[]> = [...T, ...T, ...T, ...T, ...T, ...T, ...T, ...T, ...T, ...T]
type FromDigits<S extends string, Acc extends unknown[] = []> = S extends `${infer D extends number}${infer Rest}`
? FromDigits<Rest, [...Times10<Acc>, ...Tuple<unknown, D>]>
: Acc
type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false
type Expect<T extends true> = T
export type Fifteen = Expect<Equal<FromDigits<"1500">["length"], 1500>>
export type Big = Expect<Equal<FromDigits<"9999">["length"], 9999>>
// @ts-expect-error: Type instantiation is excessively deep and possibly infinite
const counted: Tuple<"c", 1500>["length"] = 1500
// @ts-expect-error: Type produces a tuple type that is too large to represent
const tooBig: FromDigits<"20000">["length"] = 20000

Digits reach about 10,000, where a different limit applies: a tuple type may not be larger than that. For FromDigits<"20000"> the error changes from “excessively deep” to “too large to represent”. Tuples are the wrong tool for values that large.

Past tuples: digit-wise arithmetic on strings

Section titled “Past tuples: digit-wise arithmetic on strings”

For big numbers, drop tuples as the representation and keep the number as a string of decimal digits, then do what you did in primary school: add digit by digit with a carry. Tuples are used only for one digit at a time, so they never grow past 19 elements. This is a sketch. It handles non-negative integers without leading zeros, and nothing else:

type Tuple<T, N extends number, Acc extends T[] = []> = Acc["length"] extends N ? Acc : Tuple<T, N, [...Acc, T]>
type DigitOf = { 0: "0"; 1: "1"; 2: "2"; 3: "3"; 4: "4"; 5: "5"; 6: "6"; 7: "7"; 8: "8"; 9: "9" }
type DigitTuple<D extends string> = D extends `${infer N extends number}` ? Tuple<unknown, N> : never
type Ten = Tuple<unknown, 10>
type AddDigits<A extends string, B extends string, Carry extends 0 | 1> = [
...DigitTuple<A>,
...DigitTuple<B>,
...Tuple<unknown, Carry>,
] extends infer Sum extends unknown[]
? Sum extends [...Ten, ...infer Rest]
? [Rest["length"] extends keyof DigitOf ? DigitOf[Rest["length"]] : never, 1]
: [Sum["length"] extends keyof DigitOf ? DigitOf[Sum["length"]] : never, 0]
: never
type Head<S extends string> = S extends `${infer H}${string}` ? H : "0"
type Tail<S extends string> = S extends `${string}${infer T}` ? T : ""
type Reverse<S extends string, Acc extends string = ""> = S extends `${infer H}${infer T}` ? Reverse<T, `${H}${Acc}`> : Acc
type AddReversed<A extends string, B extends string, Carry extends 0 | 1 = 0, Out extends string = ""> = [A, B] extends ["", ""]
? Carry extends 1
? `${Out}1`
: Out
: AddDigits<Head<A>, Head<B>, Carry> extends [infer D extends string, infer C extends 0 | 1]
? AddReversed<Tail<A>, Tail<B>, C, `${Out}${D}`>
: never
type AddStr<A extends string, B extends string> = Reverse<AddReversed<Reverse<A>, Reverse<B>>>
type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false
type Expect<T extends true> = T
export type Carry = Expect<Equal<AddStr<"999", "1">, "1000">>
export type Uneven = Expect<Equal<AddStr<"5", "17">, "22">>
export type Huge = Expect<
Equal<AddStr<"123456789012345678901234567890", "987654321098765432109876543210">, "1111111110111111111011111111100">
>

The loop runs once per digit, and each step is a tail call, so the depth limit applies to the number of digits and not to the value. The sum above has 31 digits and its value is far past anything a tuple could hold. Subtraction and comparison work the same way. Multiplication and division get long quickly, and at that point a runtime function is the better answer.

A type that compiles can still be slow. Performance introduced --extendedDiagnostics, and it works with TypeScript 7.0.2. Two versions of Range<0, 500> show what to look for. One carries the tuple in the accumulator. The other keeps only a number and rebuilds the tuple from scratch at every step with Add:

type Tuple<T, N extends number, Acc extends T[] = []> = Acc["length"] extends N ? Acc : Tuple<T, N, [...Acc, T]>
type Add<A extends number, B extends number> = [...Tuple<unknown, A>, ...Tuple<unknown, B>]["length"]
type RangeFast<To extends number, Cur extends unknown[] = [], Out extends number = never> = Cur["length"] extends To
? Out | To
: RangeFast<To, [...Cur, unknown], Out | Cur["length"]>
type RangeSlow<To extends number, I extends number, Out extends number = never> = I extends To
? Out | To
: Add<I, 1> extends infer Next extends number
? RangeSlow<To, Next, Out | I>
: never
declare const fast: RangeFast<500>
declare const slow: RangeSlow<500, 0>
const a: typeof fast = 1
const b: typeof slow = 1

Each ran alone in a small project, with a baseline of 515 instantiations for an empty program:

Instantiations Check time
RangeFast<500> 131,753 0.20s
RangeSlow<500, 0> 1,009,034 1.29s

Same answer, nearly eight times the instantiations. RangeSlow redoes an O(n) tuple build for each of the 500 steps, so the cost is quadratic, and RangeFast reuses the tuple it already has. The lesson is the same as for runtime code: carry the state, do not recompute it. Read the Instantiations line, not the clock, because the clock is noisy and the count is not.

The compiler also caches. An alias instantiated twice with the same arguments is computed once, so naming an intermediate result with a type alias is a cache. Measured the same way, one Add<400, 300> costs 87,521 instantiations, a hundred identical uses cost 88,115, and a hundred different ones (Add<400, 300>, Add<401, 300>, …) cost 519,854 and 0.85s. When one expensive type is used in many places, give it a name and use the name. When the arguments change each time, the cost does too.

The starter’s Tuple is the naive version, so it fails for lengths past a few dozen, and Add, Subtract, LessThan and Range are stubs. Rebuild Tuple with an accumulator, write the arithmetic on top of it, and implement the three value-level helpers. The type tests use lengths of 500 on purpose. They fail for the naive version, and they pass in the browser’s TypeScript 5.9 and in the local 7.0.

  • A number in a type is a tuple length. Tuple<T, N> builds one, Add spreads two, Subtract and LessThan pattern-match on a prefix.
  • Guard number first: Tuple<T, number> is T[], not [].
  • Range<1, N> turns a literal count into a union of valid indexes, so attempt 4 of 3 is a compile error.
  • A recursive call in tail position, with state in an accumulator, runs in a loop. Measured with 7.0.2 and 5.9.3: about 1000 iterations for tail calls, about 50 levels for nested ones. Treat the numbers as approximate and version-bound.
  • To go past the limit, take bigger steps (digits instead of units). A tuple type cannot exceed about 10,000 elements.
  • For huge numbers, keep strings of digits and add with a carry. Tuples then only ever hold one digit.
  • Measure with --extendedDiagnostics and watch Instantiations. Carry state instead of recomputing it, and name repeated results.