網站搜尋

typescript - typeof a == "array" 有什麼問題?


在遊樂場試試:

typeof a == "array"

將導致

運算子 '==' 無法應用於類型 '"string" | "number" | "symbol" | "object" | "function"' 與 '"array"'。

這個錯誤訊息不僅對我毫無意義(typeof a == "object" 完全沒問題),而且似乎也是最近的變動。你現在必須使用 a instanceof Array,而我上次查看時根本不需要這樣做。你能向我解釋一下嗎?

答案#1

如 SLaks 所指出,typeof 運算子永遠不會返回「array」。https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

它從未起作用過,但 TypeScript 直到 2.0 才足夠聰明來提醒你這一點。

答案#2

這裡有一個完整的可運行範例給你:

var a: string | string[];

// You need this in the example to ensure the compiler won't determine that a
// is never a string if you set it to an array...
if (new Date().getDay() > 3) {
    a = 'a string';
} else {
    a = [
        'an',
        'array'
    ];
}

if (Array.isArray(a)) {
    var example1 = a; // example1: string[]
} else {
    var example2 = a; // example2: string
}

中間的程式碼區塊僅用於示範目的,如果你以 var a: string | string[]=[] 開始這個範例,變數 example2 實際上會成為 never 類型,因為編譯器足夠聰明,能夠看出沒有任何情況下 a 變數會被設為除陣列之外的任何值。