首页 > 解决方案 > 尽管有类型保护,Typescript 仍会引发“对象可能为‘null’”错误

问题描述

我有一个我不理解的 Typescript 行为,我想听听你的意见。

即使之前进行了类型检查,编译器也会向我抛出“ Object is possible 'null' ”错误。

这是一个简化的示例:

class Bar {
  public a: string
}

class Foo {
  public bar: Bar | null
}

function functionDoingSomeStuff(callback: any) {
  callback()
}

const foo = new Foo()
if (!foo.bar) {
  return new Error()
}

console.log(foo.bar.a) // no compiler error thanks to the previous if

if (foo.bar) {
  functionDoingSomeStuff(() => {
    console.log(foo.bar.a) // a compiler error
  })
  console.log(foo.bar.a) // no compiler error
}

那么,如果我在函数调用中访问可能为 null 的属性,即使捕获if检查了它,为什么编译器会警告我呢?

提前致谢!

标签: typescripttypesnull

解决方案


这是设计使然。TypeScript 不假设类型保护在回调中保持活跃,因为做出这种假设是危险的。

使固定

在本地捕获变量以确保它不会被外部更改,TypeScript 可以很容易地理解这一点。

if (foo.bar) {
  const bar = foo.bar;
  functionDoingSomeStuff(() => {
    console.log(bar.a) // no compiler error
  })
}

推荐阅读