ts怎么生成一个40长度的元组?

STAR
  • 151
let tuple:[string,string] = ['hh','123']

上面是一个长度为2的元组,如果我想要一个长度为40,里面都是string类型的元组,我该怎么做?

回复
阅读 1.3k
5 个回答

这可以通过递归来实现,如下:

type GeneraterTuple<
  T,
  N extends number,
  R extends Array<T> = []
> = R['length'] extends N ? R : GeneraterTuple<T, N, [T, ...R]>

type StringTuple40 = GeneraterTuple<string, 40>

TS Playground


这里提供一种思路,可以通过扩展运算符来简化这种实现:

type MergeTuple<T extends any[], P extends any[]> = [...T, ...P];

type DoubleTuple<T> = T extends any[] ? MergeTuple<T, T> : MergeTuple<[T], [T]>;
type FourfoldTuple<T> = DoubleTuple<DoubleTuple<T>>;
type EightfoldTuple<T> = DoubleTuple<FourfoldTuple<T>>;
type TenfoldTuple<T> = MergeTuple<EightfoldTuple<T>, DoubleTuple<T>>;

type FourtyTuple<T> = MergeTuple< MergeTuple<TenfoldTuple<T>, TenfoldTuple<T> >, MergeTuple< TenfoldTuple<T>, TenfoldTuple<T>>>;

const a: FourtyTuple<number> = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39] // ok
const b: FourtyTuple<number> = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38] // error
const c: FourtyTuple<number> = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,''] // error

type M = {

length: 3;
0: string;

}

从概念上讲,元组是类型不同的元素线性集合。在typescript中好像确实没有限定数组长度的约束(毕竟JavaScript不太需要提前确定数组所需的内存空间大小)。

根据你的需求,尽量还是使用逻辑去控制,不能过分依赖类型系统。

const ls = [1, 2, 3, 4, 5, 6 ] as const;
你知道吗?

宣传栏