为什么 TypeScript 编译器编译它的可选的链接和空合并 https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html运营商,?.
and ??
, to
// x?.y
x === null || x === void 0 ? void 0 : x.y;
// x ?? y
x !== null && x !== void 0 ? x : y
代替
// x?.y
x == null ? void 0 : x.y
// x ?? y
x != null ? x : y
?
可能性是在幕后== null
执行相同的两次检查,但即使出于代码长度的考虑,单次检查似乎会更干净。当使用可选链接字符串时,它也会添加更少的括号。
顺便说一句,我也很惊讶可选链不能编译为
x == null ? x : x.y
保存null
vs undefined
。此后已得到答复:为什么 JavaScript 的可选链使用 undefined 而不是保留 null? https://stackoverflow.com/q/69856082/3120446
您可以在以下位置找到权威答案微软/TypeScript#16 https://github.com/microsoft/TypeScript/issues/16(哇,好旧的);具体解释在这条评论 https://github.com/microsoft/TypeScript/issues/16#issuecomment-515694505:
那是因为document.all
[...],这是一种为了向后兼容而在语言中得到特殊对待的怪癖。
document.all == null // true
document.all === null || document.all === undefined // false
在可选链提案中
document.all?.foo === document.all.foo
but document.all == null ? void 0 : document.all.foo
会错误地返回void 0
.
所以有一个特别的 https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot特殊的、不赞成的、过时的、古怪的遗产伪财产 https://stackoverflow.com/questions/33075262/what-is-an-internal-slot-of-an-object-in-javascript类型的边缘情况HTMLAllCollection https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#the-htmlallcollection-interface没有人使用,这大致等于null
但并不严格等于其中任何一个undefined
or null
。惊人的!
似乎没有人认真考虑过breaking东西为document.all
。并且自从xxx === null || xxx === undefined
版本适用于所有情况,这可能是发出向后兼容的 JS 代码的最简洁的方式,该代码的行为符合规范。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)