Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript error when using the Spread operator?

People also ask

Can I use spread operator in TypeScript?

Spreading Arrays When spreading an array, all of the elements in the array will be copied into the new array. If we have multiple arrays that we want to combine, we can use the spread operator to combine them to form a new array. console. log(thirdArr); // [1, 2, 3, 4, 5, 6];

Can you spread types in TypeScript?

If we are using TypeScript version 4 or beyond, we can spread tuple generic parameter types. This is useful to help TypeScript better infer types on expressions that involve tuples.

Does IE 11 support spread operator?

Spread properties is a part of ECMAScript 2018 which is not supported by IE. You can use Babel to transpile it.

What is the syntax for the spread operator?

JavaScript ES6 (ECMAScript 6) introduced the spread operator. The syntax is three dots(...) followed by the array (or iterable*). It expands the array into individual elements. So, it can be used to expand the array in a places where zero or more elements are expected.


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


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

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.