简体   繁体   中英

Is the spread / rest operator necessary for typescript array declarations?

Reading through some code that looks like this:

export function printAdd(...numbers: number[]) {
    alert(`Adding the numbers: ${numbers.join(', ')}`);
}

Is the ... in ...numbers necessary. IIUC that means that numbers is an array, but we are also declaring that with number[] , so it seems we are double dipping?

Is the ... in ...numbers necessary?

No, but the answer to this question depends entirely on your intended use of the parameters.

In the example you cited, the ... indicates a rest parameter . Using this will group all arguments specified when invoking the function in an array of the specified type (in this case the type is number ). Consider the following example function and invocations:

export function printAdd(...numbers: number[]) {
    alert(`Adding the numbers: ${numbers.join(', ')}`);
}

printAdd(1, 2, 3);    // Valid because there are 0 or more arguments of type number
printAdd([1, 2, 3]);  // Not valid because there is a single argument and it is of type number[]

Not using a rest parameter indicates to the compiler that the function expects to receive a single argument of type number[] .

export function printAdd(numbers: number[]) {
    alert(`Adding the numbers: ${numbers.join(', ')}`);
}

printAdd(1, 2, 3);    // Not valid because there are 3 arguments of type number
printAdd([1, 2, 3]);  // Valid because there is a single argument of type number[]

This is made more obvious by analyzing the output of the Typescript compiler. When compiled, the first example becomes:

// COMPILER OUTPUT
function printAdd() {
    var numbers = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        numbers[_i] = arguments[_i];
    }
    alert("Adding the numbers: " + numbers.join(', '));
}

Note the use of the arguments object. This is an array-like object but it is not an array. Meaning you can't use any of the Array.prototype methods on it.

The second example becomes

// COMPILER OUTPUT
function printAdd(numbers) {
    alert("Adding the numbers: " + numbers.join(', '));
}

The arguments object is not used and numbers is an Array , so Array.prototype methods are immediately available for use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM