Construct Tuple
Less than 1 minuteTC-Medium
Construct Tuple
Problem
Construct a tuple with a given length.
type result = ConstructTuple<2> // [unknown, unknown]Solution
Approach: Accumulator until Target Length
Recursively grow a tuple until its length equals L.
type ConstructTuple<
L extends number,
T extends unknown[] = []
> = T['length'] extends L
? T
: ConstructTuple<L, [...T, unknown]>How it works:
- Start with an empty tuple
T = []. - If
T['length'] === L, returnT. - Otherwise, append one
unknownand recurse.
Key Takeaways
- This is the fundamental "build a tuple of length N" pattern that underpins type-level arithmetic throughout TypeScript challenges.
- The accumulator
Tdoubles as both the result and the counter.
