[FIXED] Typescript: dynamically define a length of a returned tuple/array based on tuple/array function args


Consider the following typescript code:

function concatTuples<T>(first: [...T[]], second: [...T[]]): [...T[]] {
  return [...first, ...second];

const result = concatTuples([0, 1], [2, 3]);

So the function joins tuples. Currently there is no way of knowing what the lenght of the returned tuple is.

Current type of result: number[].

What I’d like the type to be : [number, number, number, number].

So that the size of the returned tuple/array needs to be dynamically infered from function arguments.

Is there any way of achieving this? I looked around the docs and didn’t find any straightforward solution.


You’re not really using tuple types in your code; the T type parameter is just the element type, and the tuple type consisting of only the rest element [...T[]] is immediately reduced to the unordered and arbitrarily-long array type T[]. Thus your code is just accepting two arrays of type T[] and returning another one.

To support your use case you want to use variadic tuple types, and will need two type parameters: one for each array type (and not their elements). It looks like this:

function concatTuples<T extends any[], U extends any[]>(
  first: [...T], second: [...U]
): [...T, ...U] {
    return [...first, ...second];

And now things work as you intended:

const result = concatTuples([0, 1], [2, 3]);
// const result: [number, number, number, number]

Playground link to code

Answered By – jcalz

Answer Checked By – Senaida (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published