簡體   English   中英

打字稿數組聲明是否需要傳播/休息運算符?

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

通讀一些看起來像這樣的代碼:

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

... in ...numbers必要的。 IIUC 這意味着 numbers 是一個數組,但我們也用number[]聲明它,所以看起來我們是雙重浸漬?

... in ...數字是必要的嗎?

不,但這個問題的答案完全取決於您對參數的預期用途。

在您引用的示例中, ...表示休息參數 使用 this 會將調用函數時指定的所有參數分組到指定類型的數組中(在這種情況下,類型為number )。 考慮以下示例函數和調用:

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[]

不使用 rest 參數向編譯器表明該函數期望接收類型為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[]

通過分析 Typescript 編譯器的輸出,這一點變得更加明顯。 編譯后,第一個示例變為:

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

注意arguments對象的使用。 這是一個類似數組的對象,但它不是數組。 這意味着您不能在其上使用任何Array.prototype方法。

第二個例子變成

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

不使用arguments對象,並且numbers是一個Array ,因此Array.prototype方法可以立即使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM