首页 > 解决方案 > Typescript中的Concat元组类型?

问题描述

type T1 = ['a','b','c']
type T2 = ['d','e','f']
type TN = [.., .., ..]

type M = Concat<T1,T2,...,TN> //or Concat<[T1,T2,...,TN]>
//get ['a','b','c','d','e','f',...]

type Error =[...T1,...T2,...T3,...]//A rest element must be last in a tuple type.

我想将许多元组类型连接到一个元组中。如何定义类型Concat<>

标签: typescript

解决方案


使用递归条件类型(TS 4.1.0),您将能够:

type T1 = ['a', 'b', 'c']
type T2 = ['d', 'e', 'f']
type TN = [1, 2, 3]

type Concat<T> = T extends [infer A, ...infer Rest]
    ? A extends any[] ? [...A, ...Concat<Rest>] : A
    : T;

type C = Concat<[T1, T2, TN]>; // ["a", "b", "c", "d", "e", "f", 1, 2, 3]

操场


推荐阅读