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

I want concat many tuple types into one tuple. How to define type Concat<>?

0

2 Answers 2

5

With recursive conditional types (TS 4.1.0), you'll be able to:

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]

Playground

Sign up to request clarification or add additional context in comments.

Comments

3

You can just use variadic tuple types (TS 4.0) instead of adding an additional type abstraction:

type T3 = ["g", "h", "i"]

type Concatenated = [...T1, ...T2, ...T3] // ["a", "b", ..., "h", "i"]

If there is still need for a separate Concat type, following will make use of TS 4.1 recursive conditional types and is more strict than Aleksey's answer:

// separate initial and recursive type constructor
type Concat<T extends unknown[][]> = ConcatRec<T>
type ConcatRec<T extends unknown[]> = T extends [infer I, ...infer R] ?
    I extends unknown[] ? [...I, ...ConcatRec<R>] : never
    : T

type R1 = Concat<[T1, T2, T3]>; // ["a", "b", "c", ... , "i"]
type R2 = Concat<["foo"]>; // now errors properly

For example you can combine this type with Array.prototype.concat:

function concat<T extends [unknown, ...unknown[]][]>(...t: T): Concat<T> {
    return [].concat(...t as any) as any
}

const result = concat([1, "a", 3], [true, 5, new Date()])
// const res: [number, string, number, boolean, number, Date]

Live code sample on Playground

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.