31

enter image description here 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.

3
  • 3
    Please prefer to paste code, rather than screenshot. Commented Jul 20, 2017 at 21:04
  • The code runs fine when compiled, I only get an error while I'm in the editor. Commented Jul 20, 2017 at 21:05
  • 2
    tslib version of vscode is older and cannot infer the tuple Commented Jul 20, 2017 at 21:06

3 Answers 3

30

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

Sign up to request clarification or add additional context in comments.

Comments

12

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 );

2 Comments

This is more along the lines of what I thought but TS still gives gives the same error
Same in 2020, I thought this worked for sure, instead it gives the same error
1

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.

2 Comments

VSCode is running on TypeScript 2.4.2. I updated the example I gave where I still get the error
this.drawTextTest( ...(array as [any, any, any] ))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.