這項診斷會偵測 Angular 範本中無用的空值合併運算子(??)。
具體來說,它會找出輸入值並非「可為 null」型別的運算,也就是其型別不包含 null 或 undefined 的情況。
對於這類值,?? 右側的內容永遠不會被用到。
import {Component} from '@angular/core';
@Component({
// Template displays `username` if present, falls back to 'root' if it is
// `null` or `undefined`.
template: `<div>{{ username ?? 'root' }}</div>`,
})
class MyComponent {
// `username` is declared as a `string` which _cannot_ be `null` or
// `undefined`.
username: string = 'Angelino';
}
這樣寫有什麼問題?
對不可為 null 的輸入值使用空值合併運算子不會有任何效果,而且代表值的允許型別與它在範本中的呈現方式之間存在落差。 開發者可能會合理地假設,空值合併運算子的右側在某些情況下會被顯示出來,但實際上它永遠不會顯示。 這可能會讓人對程式預期的輸出感到困惑。
我應該怎麼做?
讓範本與宣告的型別保持一致。 仔細檢查輸入值的型別,確認它是否真的預期可以為 null。
如果輸入值應該可以為 null,就把 null 或 undefined 加入它的型別來表明這一點。
import {Component} from '@angular/core';
@Component({
template: `<div>{{ username ?? 'root' }}</div>`,
})
class MyComponent {
// `username` is now nullable. If it is ever set to `null`, 'root' will be
// displayed.
username: string | null = 'Angelino';
}
如果輸入值_不_應該可以為 null,就刪除 ?? 運算子及其右側運算元,因為 TypeScript 保證該值永遠不會是 null。
import {Component} from '@angular/core';
@Component({
// Template always displays `username`, which is guaranteed to never be `null`
// or `undefined`.
template: `<div>{{ username }}</div>`,
})
class MyComponent {
username: string = 'Angelino';
}
設定需求
任何擴充診斷要發出訊息,都必須啟用 strictTemplates。
要發出 nullishCoalescingNotNullable 診斷,還必須啟用 strictNullChecks。
如果無法避免,該怎麼辦?
可以透過編輯專案的 tsconfig.json 檔案來停用這項診斷:
{
"angularCompilerOptions": {
"extendedDiagnostics": {
"checks": {
"nullishCoalescingNotNullable": "suppress"
}
}
}
}
詳情請見擴充診斷設定。