尝试在playground:typeof == ==“array”有什么问题?
typeof a == "array"
将导致
操作 '==' 不能应用于类型“ “串” | “数字”| “符号”| “对象”| “功能””和‘‘阵列’’)。
不但没有此错误消息是没有意义的,我(typeof a == "object"
就好了),这似乎是一个近期的变化了。你现在必须使用a instanceof Array
,这是没有必要上次我检查。你能向我解释一下吗?
尝试在playground:typeof == ==“array”有什么问题?
typeof a == "array"
将导致
操作 '==' 不能应用于类型“ “串” | “数字”| “符号”| “对象”| “功能””和‘‘阵列’’)。
不但没有此错误消息是没有意义的,我(typeof a == "object"
就好了),这似乎是一个近期的变化了。你现在必须使用a instanceof Array
,这是没有必要上次我检查。你能向我解释一下吗?
正如SLak指出的那样,typeof运算符永远不能返回“array”。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
它从来没有工作,但TypeScript只是变得足够聪明,在2.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
变量将被设置为除数组以外的任何其他情况。
'typeof'运算符永远不能返回它。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof – SLaks
啊,我明白了,谢谢。有趣的是这在以前的版本中从来都不是问题 – Blauhirn
它从来没有工作过,但是TypeScript只是变得足够聪明,可以在2.0中提醒你。 – SLaks