【发布时间】:2018-03-03 15:45:58
【问题描述】:
如果我有一个实例函数来检查属性是否不为空,如果我在条件中使用该函数,TypeScript 会给出错误“对象可能为空”。但是,如果我直接检查 null,则不会发生错误。我该如何解决这个问题?
type SomeType = {
someFunc: Function;
}
class A {
bar: SomeType | null;
constructor() {
this.bar = null;
}
hasBar() {
return this.bar !== null;
}
}
const a = new A();
if (a.hasBar()) {
a.bar.someFunc(); // Throws object possibly null error
}
if (a.bar !== null) {
a.bar.someFunc(); // Throws no error
}
typescript playground 的链接:Here(在选项中打开 strictNullChecks)
【问题讨论】:
-
a.bar!.someFunc()。 typescriptlang.org/docs/handbook/…
-
我不想改变条件,我想使用 a.hasBar() 函数。
-
那又怎样?我在哪里建议不要使用 a.hasBar()?你真的看过我的评论吗?
标签: typescript