logoProsperBao

Construct Tuple

Apr 27, 2022

题目来源(type-challenges)

问题

构造一个指定长度的元组

type case1 = ConstructTuple<0> //  []
type case2 = ConstructTuple<2> //  [unknown, unknown]
type case3 = ConstructTuple<999>['length'] // 999
  // @ts-expect-error
type case4 = ConstructTuple<1000>['length'] // 1000

解答

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

拆分

  1. 递归数组
>
CC BY-NC-SA 4.0 2021-PRESENT © Prosper Bao