Typescript 检查实例函数中的null会得到;对象可能为空”;错误

Typescript 检查实例函数中的null会得到;对象可能为空”;错误,typescript,Typescript,如果我有一个实例函数,该函数检查属性是否为null,那么如果我在条件中使用该函数,TypeScript会给出一个错误“Object albible null”。但是,如果我直接检查null,则不会发生错误。我怎样才能解决这个问题 type SomeType = { someFunc: Function; } class A { bar: SomeType | null; constructor() { this.bar = null; }

如果我有一个实例函数,该函数检查属性是否为null,那么如果我在条件中使用该函数,TypeScript会给出一个错误“Object albible null”。但是,如果我直接检查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:(在选项中打开strictNullChecks)

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

唯一能对流量分析产生影响的功能类型是类型保护:

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
}
函数hasValue(v:T | null):v是T{
返回v!==null;
}
常数a=新的a();
如果(hasValue(a.bar)){
a、 bar.someFunc();//a.bar不为null
}

a.bar!。someFunc()。我不想更改条件,我想使用a.hasBar()函数。那又怎样?我在哪里建议不要使用a.hasBar()?你真的读过我的评论吗?