这是一个咖啡错误吗?解构与存在算子

Is it a coffeescript bug? Destructuring and Existential Operator

以下 coffeescript 代码:

{ baz } = @foo.bar?

产生:

var baz;
baz = (this.foo.bar != null).baz;

但我预计:

var ref, baz;
if ((ref = this.foo.bar) != null) {
  baz = ref.baz;
}

这是错误还是预期行为?

我认为您将一元 ? 运算符与二元 ?. 运算符混淆了。

这个表达式的右边:

baz = @foo.bar?.baz

...使用二进制 ?. 运算符。如您所知,它 returns 后续 属性 的值(如果存在)和 null 否则(并短路进一步属性的评估)。

另一方面,此表达式的 RHS:

{ baz } = @foo.bar?

...使用一元 ? 运算符。如果其操作数(前面的表达式)是 nullundefined,则它 returns false,否则 true

这是一个非常容易犯的错误;你可以在 this CoffeeScript issue. Compounding the problem, the CoffeeScript docs don't even give these two operators different names. They call ? the "existential operator"?. 和 "accessor variant of the existential operator."

中看到有人问同样的问题