3

How to merge tuples together? I need to add one tuple after end of another like below.

type MergeTuple<A extends any[], B extends any[]> = [...A, ...B];

Only thing that works is this:

type MergeTuple<A extends any[], B extends any[]> = [A[0], B[0]];

But that works with static count of items

MergeTuple<['a'], ['b']> // is ['a', 'b']

Not working for this

MergeTuple<['a', 'b'], ['c']> // is ['a', 'c'] expected ['a', 'b', 'c']
2
  • you don't need Tuple types if you will use any Commented Jan 7, 2020 at 10:09
  • it doesn't need to extend any[] ... that's my defintion of a type.. i am just saying type is tuple Commented Jan 7, 2020 at 10:11

3 Answers 3

4

Concatenating Tuples in TS is currently just possible with very ugly workarounds.

Here is how one library does it

You don't want to do that yourself. Ask yourself if you really need that, and if the answer is yes, do yourself the favor and use a type library like typescript-tuple.

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

Comments

3

Does this not work for you?

type MergeTuples<
    A extends readonly any[],
    B extends readonly any[]
> = [...A, ...B];

Here is a playground if needed.

Comments

0

If you can get your multiple tuple fragments into array form, then you can also use a type like this for an arbitrary amount of tuple fragments:

type Flattened<Fragments extends any[][]> = 
   Fragments extends 
      [
          infer CurrentTupleFragment extends any[], 
          ...infer RemainingTupleFragments extends any[][]
      ] ? 
      [
          ...CurrentTupleFragment,
          ...Flattened<RemainingTupleFragments>
      ] : 
      [];

type flat = Flattened<[["a", "b"], ["c"], ["d", "e", "f"]>; //["a", "b", "c", "d", "e", "f"]

This works its magic by first recursively splitting the array into its front element CurrentTupleFragment and the remaining yet to be recursively treated elements until it hits the end of the array (the first extends clause does not match anymore) and then returning an empty array up the recursion chain. When on the way back up, we then spread out the CurrentTupleFragment and effectively prepend them to the already spread out tuple fragments from our recursion, which we of course need to spread out again, otherwise we would get ever deeper nested Arrays (try removing the ... before the recursive Flatten to see what I mean).

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.