Reputation:
Whenever I use the spread operator such as below
public drawTextTest(p1: number, p2: number, p3: number):void {
console.log(p1, p2, p3);
}
let array = [2, 2, 5];
this.drawTextTest( ... array );
I get this error in the editor
[ts] Expected # arguments, but got a minimum of 0.
Why does TypeScript give an error when using the spread operator to pass arguments?
There's no error when I actually run the code, the spread operator is simply letting me use the array as arguments to a function yet in VSCode it shows me the error as if I couldn't.
Upvotes: 31
Views: 15687
Reputation: 13312
typed spread operator works only when all parameters are marked as optional
public drawTextTest(p1?: number, p2?: number, p3?: number):void {
see https://github.com/Microsoft/TypeScript/issues/4130#issuecomment-303486552
Upvotes: 30
Reputation: 294
Newer versions of TypeScript should be figuring this out through flow analysis but you should be able to get the code working by manually typing the array to the following way to ensure the min length:
function drawTextTest(p1: number, p2: number, p3: number):void {
console.log(p1, p2, p3);
}
let array: [number, number, number] = [2, 2, 5];
this.drawTextTest( ... array );
Upvotes: 12
Reputation: 88
Vscode may be using a version of typescript before 2.1 to evaluate the code. Double-check the version in the bottom right of your IDE window.
If I'm wrong about that, I'll need to see your drawInfo object definition. My second guess is that drawInfo has optional properties and the evaluator is seeing the possibility that the spread would result in 0 params.
EDIT: drawInfo appears to be an array. Because the length of arrays can be changed and nothing guarantees that there are 3 properties, the ts evaluator will complain.
If the drawInfo will always contain 3 values, you may want to change it from an array to a defined type and avoid the spread operator.
Upvotes: 1