Typescript抛出一个“;对象可能是';空'&引用;错误,尽管类型为guard
我有一个打字脚本的行为,我不理解,我想有你的意见 即使之前进行了类型检查,编译器也会向我抛出一个“对象可能为‘null’”错误 以下是一个简化的示例:Typescript抛出一个“;对象可能是';空'&引用;错误,尽管类型为guard,typescript,types,null,Typescript,Types,Null,我有一个打字脚本的行为,我不理解,我想有你的意见 即使之前进行了类型检查,编译器也会向我抛出一个“对象可能为‘null’”错误 以下是一个简化的示例: class Bar { public a: string } class Foo { public bar: Bar | null } function functionDoingSomeStuff(callback: any) { callback() } const foo = new Foo() if (!foo.bar)
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检查它,为什么编译器会警告我
提前谢谢 这是设计的。TypeScript不假设类型保护在回调中保持活动状态,因为做出这种假设是危险的 修理 在本地捕获变量以确保它不会在外部被更改,TypeScript可以很容易地理解这一点
if (foo.bar) {
const bar = foo.bar;
functionDoingSomeStuff(() => {
console.log(bar.a) // no compiler error
})
}