Here is a code snippet I found on the TypeScript Playground:
function foo(a: number, b: number) {}
const msg: any = {
params: [1,2],
};
// None of these works:
foo(...msg.params); // This should work but it doesn't
foo(...(msg.params as any));
foo((...msg.params) as any);
// Only this works:
(foo as any)(...msg.params);
The error message is:
A spread argument must either have a tuple type or be passed to a rest parameter.
msg
/msg.params
are already any
. Why can't I use it for spread ...
operator and pass as function argument? Isn't it the point of any
? And why does casting the function to any
works?
The forced compiled Javascript works:
"use strict";
function foo(a, b) {
console.log(a + b);
}
const msg = {
params: [1, 2],
};
foo(...msg.params); // Logs 3 correctly