我不明白為什么!我的回呼函式中需要非空斷言運算子,因為我檢查了if之前的值。
編譯器因錯誤而失敗Object is possibly 'undefined'.
當然使用!.label作品,但我想了解為什么在這種情況下它不起作用。那是因為我的回呼函式的“新范圍”嗎?
現場演示
interface Brand {
label?: string;
}
class Component {
public brand?: Brand;
public readonly service = new Service();
public process() {
if (this.brand) {
// this.brand.label = "ok"; // Works
// this.service.process2(() => this.brand!.label = "ok"); // Works
/*
this.service.process2(() => {
if (this.brand) {
this.brand.label = "ok";
}
});
*/ // Works
this.service.process2(() => this.brand.label = "ok"); // Fails. Why ? Because of the new scope ?
}
}
}
class Service {
public process2(callback: () => void) {
callback();
}
}
// Main
const comp = new Component();
comp.brand = {
label: "foo"
};
comp.process();
它使我的 ESLint 分析失敗,因為我啟用了規則no-non-null-assertion并且我不想手動忽略這些行。
uj5u.com熱心網友回復:
所以,if (this.brand)只是保證 this.service.process2會被呼叫。
但是,當呼叫回呼時,您this.brand在內部傳遞的回呼this.service.process2可以為 null 或未定義
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/444507.html
標籤:打字稿
上一篇:如何訪問介面打字稿中的屬性
