#7544Medium

Construct Tuple

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.

Challenge Instructions: Construct Tuple

Medium

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).

ChallengeSolution
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>>,
]

Pro Challenge

Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.

One-time payment. Lifetime access.

Detailed Explanation

type ConstructTuple<L extends number, R extends unknown[] = []> =
  R['length'] extends L
    ? R
    : ConstructTuple<L, [...R, unknown]>

How it works:

This 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.

Share this challenge