Home > other >  Using Typescript variadic tuple type and Javascript Spread together
Using Typescript variadic tuple type and Javascript Spread together

Time:05-31

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)[].

CodePudding user response:

This is probably what you meant:

function concat<T extends readonly any[], U extends readonly any[]>(
  arg1: T,
  arg2: U,
): [...T, ...U] {
  return [...arg1, ...arg2]
}

T[] means "array of Ts", but not "T which is an array".

See this TypeScript playground.

CodePudding user response:

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

  • Related