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
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With