Type-Level Arithmetic With Tuple Lengths

Implement compile-time addition and subtraction by building tuple types and reading their length, keeping arithmetic in the type system.

TypescriptData Integrity

Code

typescriptsnippet
33 lines
// Type-level arithmetic: tuple length is a number
type BuildTuple<L extends number, T extends unknown[] = []> = T['length'] extends L
  ? T
  : BuildTuple<L, [...T, unknown]>;

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

type Subtract<A extends number, B extends number> = BuildTuple<A> extends [
  ...BuildTuple<B>,
  ...infer Rest,
]
  ? Rest['length']
  : never;

type Repeat<T, N extends number, R extends T[] = []> = R['length'] extends N
  ? R
  : Repeat<T, N, [...R, T]>;

function repeat<T, N extends number>(value: T, times: N): Repeat<T, N> {
  return Array.from({ length: times }, () => value) as Repeat<T, N>;
}

const total: Add<4, 3> = 7;
const gap: Subtract<10, 4> = 6;
console.log('add:', total, 'subtract:', gap);

const triple = repeat('x', 3);
console.log('tuple length:', triple.length, '| values:', triple.join(''));

// 长度类型参与条件判断
type Longer<A extends number, B extends number> = [Subtract<A, B>] extends [never] ? false : true;
const check: Longer<9, 2> = true;
console.log('longer:', check);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

add: 7 subtract: 6
tuple length: 3 | values: xxx
longer: true

What the file builds

There is one way to read it: the function repeat, doing all the work.

Putting it to use

The runtime lines echo the type-level results — add: 7 subtract: 6, tuple length: 3 | values: xxx, longer: true — so each compile-time computation has a matching printed value.

Core lines

return Array.from({ length: times }, () => value) as Repeat<T, N>;

Interactive Tools for This Topic

FAQ

Does this require external packages?
No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. The file defines `repeat` at load time.