跳到正文
本页尚未翻译成中文,以下为英文原文。 查看英文版

Unparenthesized Nullish Coalescing ​

This diagnostic detects cases where the nullish coalescing operator (??) is mixed with the logical or (||) or logical and (&&) operators without parentheses to disambiguate precedence.

ts
import {Component, input} from '@angular/core';

@Component({
  template: `<button [disabled]="hasPermission() && task()?.disabled ?? true">Run</button>`,
})
class MyComponent {
  hasPermission = input(false);
  task = input<Task | undefined>(undefined);
}

What's wrong with that? ​

Without disambiguating parentheses, its difficult to understand whether the ?? or ||/&& is evaluated first. This is considered an error in TypeScript and JavaScript, but has historically been allowed in Angular templates.

What should I do instead? ​

Always use parentheses to disambiguate in theses situations. If you're unsure what the original intent of the code was but want to keep the behavior the same, place the parentheses around the ?? operator.

ts
import {Component, input} from '@angular/core';

@Component({
  template: `<button [disabled]="hasPermission() && (task()?.disabled ?? true)">Run</button>`,
})
class MyComponent {
  hasPermission = input(false);
  task = input<Task | undefined>(undefined);
}

基于 MIT 许可证发布。