flo*_*ann 3 null types typescript
我有一个我没有理解的Typescript行为,我想对你有所了解.
即使之前有类型检查,编译器也会抛出" 对象可能为'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属性的函数调用中,即使赶上如果检查呢?
提前致谢!
这是设计的.TypeScript不会假设类型保护在回调中保持活动状态,因为这种假设很危险.
在本地捕获变量以确保它不会在外部进行更改,TypeScript可以很容易地理解它.
if (foo.bar) {
  const bar = foo.bar;
  functionDoingSomeStuff(() => {
    console.log(bar.a) // no compiler error
  })
}