0Pricing
TypeScript Academy · Lesson

Counting with Tuple Length

Represent numbers as tuple lengths in types.

Numbers Need a Representation

The type system cannot add numeric literals directly. The classic workaround is to represent a number N as a tuple with N elements. The contents do not matter; only the length does.

type Three = [unknown, unknown, unknown];
type N = Three["length"]; // 3

Reading Length

Every tuple type has a length property that is a numeric literal type. Indexing with ["length"] reads it back as a number you can use.

type A = [1, 2, 3, 4]["length"]; // 4
type B = []["length"];           // 0
type C = ["x"]["length"];        // 1

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