2017-03-03 206 views
1

嘗試在playgroundtypeof == ==「array」有什麼問題?

typeof a == "array" 

將導致

操作 '==' 不能應用於類型「 「串」 | 「數字」| 「符號」| 「對象」| 「功能」」和‘‘陣列’’)。

不但沒有此錯誤消息是沒有意義的,我(typeof a == "object"就好了),這似乎是一個近期的變化了。你現在必須使用a instanceof Array,這是沒有必要上次我檢查。你能向我解釋一下嗎?

+3

'typeof'運算符永遠不能返回它。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof – SLaks

+0

啊,我明白了,謝謝。有趣的是這在以前的版本中從來都不是問題 – Blauhirn

+4

它從來沒有工作過,但是TypeScript只是變得足夠聰明,可以在2.0中提醒你。 – SLaks

回答

0

這是給你一個完整的工作示例:

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變量將被設置爲除數組以外的任何其他情況。