TypeScript error when using Spread statement?

enter image description here Whenever I use the spread operator like below

public drawTextTest(p1: number, p2: number, p3: number):void {
    console.log(p1, p2, p3);
}
let array = [2, 2, 5];
this.drawTextTest( ... array );

      

I am getting this error in the editor

[ts] # ​​expected arguments, but received a minimum of 0.

Why does TypeScript give an error when using the spread operator to pass arguments?

There is no error when I actually run the code, the spread operator just allows me to use an array as arguments to a function, but in VSCode it shows me an error like I couldn't.

+3


source to share


3 answers


Operator

printed spread 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

+2


source


Newer versions of TypeScript should figure this out from stream parsing, but you should be able to get the code to work by manually typing the array like this to ensure the minimum 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


source


Vscode can use typescript version up to 2.1 to evaluate code. Double check the version in the lower right corner of the IDE window.

If I'm wrong about this, I'll need to see the definition of the drawInfo object. My second guess is that drawInfo has optional properties and the evaluator sees the possibility that the spread will result in 0 parameters.

EDIT: drawInfo appears to be an array. Since the length of the arrays can be changed and nothing guarantees that there are 3 properties, the ts evaluator will complain.

If drawInfo will always contain 3 values, you can change it from an array to a specific type and avoid the spread operator.

0


source







All Articles