[Typescript] 80. Medium - Construct Tuple

Construct a tuple with a given length.

For example

type result = ConstructTuple<2> // expect to be [unknown, unkonwn]

 

/* _____________ Your Code Here _____________ */

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


/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'

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

 

posted @ 2022-10-30 16:39  Zhentiw  阅读(24)  评论(0)    收藏  举报