【问题标题】:Checking for null in an instance function gets "Object possibly null" error在实例函数中检查 null 得到“对象可能为 null”错误
【发布时间】: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.hasBar() 函数。
  • 那又怎样?我在哪里建议不要使用 a.hasBar()?你真的看过我的评论吗?

标签: typescript


【解决方案1】:

这是流量分析的一个已知限制。函数内部的检查不会对函数外部产生影响。有关详细信息,请参阅此issue。

唯一可以对流分析产生影响的函数类型是类型保护:

function hasValue<T>(v: T| null): v is T {
    return v !== null;
}
const a = new A();

if (hasValue(a.bar)) {
    a.bar.someFunc(); // a.bar is not null
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-23
    • 2021-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-09
    • 2023-03-23
    相关资源
    最近更新 更多