2017-03-03 207 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变量将被设置为除数组以外的任何其他情况。