這項診斷會偵測 Angular 範本中,可選鏈結運算(.?)左側值的型別不包含 null 或 undefined 的情況。
import {Component} from '@angular/core';
@Component({
// Print the user's name safely, even if `user` is `null` or `undefined`.
template: `<div>User name: {{ user?.name }}</div>`,
})
class MyComponent {
// `user` is declared as an object which _cannot_ be `null` or `undefined`.
user: {name: string} = {name: 'Angelino'};
}
這樣寫有什麼問題?
對不可為 null 的輸入值使用可選鏈結運算子不會有任何效果,而且代表值的允許型別與它在範本中的呈現方式之間存在落差。
開發者可能會合理地假設,可選鏈結運算子的輸出有可能是 null 或 undefined,但實際上它永遠不會是這兩個值。
這可能會讓人對程式預期的輸出感到困惑。
我應該怎麼做?
讓範本與宣告的型別保持一致。 仔細檢查輸入值的型別,確認它是否真的預期可以為 null。
如果輸入值應該可以為 null,就把 null 或 undefined 加入它的型別來表明這一點。
import {Component} from '@angular/core';
@Component({
// If `user` is nullish, `name` won't be evaluated and the expression will
// return the nullish value (`null` or `undefined`).
template: `<div>{{ user?.name }}</div>`,
})
class MyComponent {
user: {name: string} | null = {name: 'Angelino'};
}
如果輸入值不應該可以為 null,就刪除 ? 運算子。
import {Component} from '@angular/core';
@Component({
// Template always displays `name` as `user` is guaranteed to never be `null`
// or `undefined`.
template: `<div>{{ user.name }}</div>`,
})
class MyComponent {
user: {name: string} = {name: 'Angelino'};
}
設定需求
任何擴充診斷要發出訊息,都必須啟用 strictTemplates。
要發出 optionalChainNotNullable 診斷,還必須啟用 strictNullChecks。
如果無法避免,該怎麼辦?
可以透過編輯專案的 tsconfig.json 檔案來停用這項診斷:
{
"angularCompilerOptions": {
"extendedDiagnostics": {
"checks": {
"optionalChainNotNullable": "suppress"
}
}
}
}
詳情請見擴充診斷設定。