【发布时间】:2021-11-05 16:06:17
【问题描述】:
这是我在 Why does the TypeScript compiler compile its optional chaining and null-coalescing operators with two checks? 末尾顺便问的一个后续问题,正如常驻 TypeScript 传奇人物 jcalz 在评论中指出的那样,它确实值得提出自己的问题。
// Why does the JavaScript treat
x?.y
// as
x === null || x === void 0 ? void 0 : x.y
// instead of
x === null || x === void 0 ? x : x.y
// ?
当x == null 时,后者将保留null,而前者始终返回undefined。
现代浏览器原生支持?.,因此我们可以测试这种行为。
const test = () => {
console.log('undefined?.x\t\t==>\t', undefined?.x);
console.log('null?.x\t\t\t==>\t', null?.x);
console.log('null?.x === null\t==>\t', null?.x === null);
};
try {
eval('null?.x');
test();
} catch {
console.error('Your browser does not support optional chaining syntax.');
console.info('While optional chaining is supported by all modern browsers, this will not work in browsers that do not support the syntax.')
console.warn('????');
console.info('Shocking, I know.');
console.info('Compatibility chart: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining#browser_compatibility');
}
【问题讨论】:
-
正如我在另一个问题中所说,这就是 optional chaining 在 JS 中的工作方式;
null?.x是undefined而不是null。那么您是在问为什么 TS 决定实施降级以生成符合 JS 规范的代码? (答案:当 TS 不正确地降级时,它会让小猫伤心????)或者你是在问为什么 JS 决定对undefined进行可选链接短路,而不是保留传入的无效性的特殊味道? (答案:还不确定) -
啊,回答:github.com/tc39/proposal-optional-chaining#faq
null?.x是undefined因为null的x属性将是undefined,而不是null,如果你可以取消引用null任何其他缺少x属性的东西。 -
啊,有一个 process 用于向 JS 引入功能。一旦提案达到“阶段 3”,意味着它很可能在不久的将来出现在 JS 中,并且它的细节大多是稳定的。此时,TS 根据规范实现它。因此,虽然从某种意义上说,“TS 先有它”在技术上是正确的,即 TS 版本在正式成为 EcmaScript 规范的一部分之前就具有该功能,但他们不能随意选择它会做什么。
-
所以,我很乐意回答,但这与 TypeScript 本身并没有多大关系;也许您应该将问题编辑为关于 JS 的问题?
-
我把它更新为关于 JS
标签: javascript language-design