Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spread rest with TypeScript complains about signature of call target

I have a function defined this way:

function create(element1: number, ...otherElements: any[]) {
  // Do something
  return makeSomething(...otherElements)
}


function makeSomething(a: string, b: number, c: IElements) {
  // Do something
}

TypeScript complains about the parameters I pass to makeSomething

error TS2346: Supplied parameters do not match any signature of call target.

What is the right way to do define such thing while still using the spread syntax?

Thanks

like image 493
alexmngn Avatar asked Jun 27 '17 15:06

alexmngn


1 Answers

One of the problems here is that Typescript has no idea how many items are in ...otherElements: any[]. It can't guarantee there will be 3 items to pass to makeSomething, even though the item type (any) would be valid for the arguments.

You can trivially work around that by telling it there are, in fact, 3 elements:

function create(element1: number, ...otherElements: any[]) {
  // Do something
  const [a, b, c] = otherElements;
  return makeSomething(a, b, c)
}

This allows you to add defaults for missing ones, error checking, etc, but most importantly, having three explicit elements satisfies the type check.

If you want to pass the remaining arguments as well, simple add a rest parameter to the destructure:

function create(element1: number, ...otherElements: any[]) {
  // Do something
  const [a, b, c, ...d] = otherElements;
  return makeSomething(a, b, c, ...d)
}
like image 70
ssube Avatar answered Oct 06 '22 00:10

ssube