Construct a tuple with a given length. Learn tuple manipulation in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll implement ConstructTuple<L> which builds a tuple of unknown elements with exactly the specified length.
Construct a tuple with a given length.
For example
[object Object]Change the following code to make the test cases pass (no type check errors).
type cases = [
Expect<Equal<ConstructTuple<0>, []>>,
Expect<Equal<ConstructTuple<2>, [unknown, unknown]>>,
Expect<Equal<ConstructTuple<999>['length'], 999>>,
// @ts-expect-error
Expect<Equal<ConstructTuple<1000>['length'], 1000>>,
]
Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.
One-time payment. Lifetime access.
type ConstructTuple<L extends number, R extends unknown[] = []> =
R['length'] extends L
? R
: ConstructTuple<L, [...R, unknown]>How it works:
R that starts as an empty array []R['length'] extends L checks if the accumulator has reached the desired lengthRunknown element with [...R, unknown]LConstructTuple<1000> will trigger a ts-expect-error as expected in the test casesThis challenge helps you understand recursive tuple construction and accumulator patterns in TypeScript's type system and how to apply this concept in real-world scenarios.
This challenge is originally from here.