擴充診斷

空值合併運算子未加括號

這項診斷會偵測空值合併運算子(??)與邏輯 or(||)或邏輯 and(&&)運算子混用,卻沒有用括號來明確區分優先順序的情況。

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);
}

這樣寫有什麼問題?

如果沒有用括號明確區分,就很難理解到底是先求值 ??,還是先求值 ||/&&。 這在 TypeScript 與 JavaScript 中會被視為錯誤,但在 Angular 範本中過去一直是被允許的。

我應該怎麼做?

在這類情況下,務必使用括號來明確區分。如果你不確定程式碼原本的意圖,但想保持行為不變,就把括號加在 ?? 運算子的周圍。

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);
}