在做一些打字稿时,我遇到了我以前在 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'
吗?如果不是,哪一个更好,为什么?
谢谢
有差异。
如果您正在检查全局变量
x
,
然后 typeof x === 'undefined'
将返回 true
并 x === void 0
抛出 ReferenceError
。window.x === void 0
才能获得 true
。 然而在这种情况下,它知道 x
至少会被设置为 undefined
,因为它是一个函数参数,所以错误永远不会成为问题。
我认为为了可读性,我更愿意使用
typeof x === 'undefined'
。