在做一些打字稿时,我遇到了以前在javascript中看不到的东西。
constructor(public x: number = 0, public y: string = "none"){
this.color = "red";
}
该部分正在编译成:
if (x === void 0) { x = 0; }
if (y === void 0) { y = "none"; }
但不应该是typeof x === 'undefined'
吗?如果没有,哪一个更好,为什么?
感谢
答案 0 :(得分:2)
存在差异。
如果您正在检查全局变量x
,
然后typeof x === 'undefined'
将返回true
而x === void 0
会返回ReferenceError
您需要使用window.x === void 0
来获取true
。但是在这种情况下,它知道x
至少会被设置为undefined
,因为它是一个函数参数,因此错误永远不会成为问题。
我认为为了便于阅读,我更倾向于使用typeof x === 'undefined'
。