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