Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Typescript variadic tuple type and Javascript Spread together

Tags:

typescript

Need help understanding how the below piece of code works.

function concatFun<T extends any[], U extends any[]>(
  arg1: T[],
  arg2: U[]
): [...T, ...U] {
  const newArr = [...arg1, ...arg2]; // (T | U)[]
  return newArr; // error Type '(T | U)[]' is not assignable to type '[...T, ...U]'.
                 // Target requires 2 element(s) but source may have fewer.
}

I wanted the return type to be [...T, ...U], but the return type is (T | U)[].

like image 739
nitte93 Avatar asked Dec 03 '25 04:12

nitte93


1 Answers

FIXED You need to infer literal type of provided arguments

type Json =
  | null
  | string
  | number
  | boolean
  | Array<JSON>
  | {
    [prop: string]: Json
  }

function concatFun<
  Fst extends Json, T extends Fst[],
  Scd extends Json, U extends Scd[]>(
    arg1: [...T],
    arg2: [...U]
  ): [...T, ...U] {
  return [...arg1, ...arg2]

}

concatFun([1, 2, 3], [4, 5, 6]) // [1, 2, 3, 4, 5, 6]

Playground

Update

function concatFun<
  Fst extends Json, T extends Fst[],
  Scd extends Json, U extends Scd[]>(
    arg1: [...T],
    arg2: [...U]
  ) {
  const foo: [...T, ...U] = [...arg1, ...arg2]
  return foo
}
}

You can help TS to infer concatenated array. To be honest, I'm not sure how TS resolves it unfer the hood. But error message is pretty intuitive if you will et rid of explicit type [...T, ...U] from foo

like image 137
captain-yossarian Avatar answered Dec 08 '25 00:12

captain-yossarian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!