Typescript类型保护和胖箭头函数
这不是应该正确编译吗?我收到一个错误,突出显示的行中的类型“object”上不存在属性“hello”。 我可以在fat arrow函数之外访问Typescript类型保护和胖箭头函数,typescript,typeguards,Typescript,Typeguards,这不是应该正确编译吗?我收到一个错误,突出显示的行中的类型“object”上不存在属性“hello”。 我可以在fat arrow函数之外访问g.hello,没有问题 class Test { constructor() { } hello() : string { return "Hello"; } } let g : object; if (g instanceof Test) { () => { g.hell
g.hello
,没有问题
class Test {
constructor() {
}
hello() : string {
return "Hello";
}
}
let g : object;
if (g instanceof Test) {
() => {
g.hello(); ////// ERROR HERE /////
};
}
类型保护对变量(或任何其他对象)所做的缩小不会跨越功能边界。这是一个设计限制 解决此问题的一种方法是将
g
分配给一个新变量,该变量将根据变窄情况推断其类型。在arrow函数中访问新变量将按预期工作:
class Test {
constructor() {
}
hello() : string {
return "Hello";
}
}
let g : object;
if (g instanceof Test) {
const gTest = g;
() => {
gTest.hello();
};
}
如果g
没有改变,解决此问题的另一种方法是使用const
声明g
。这将使编译器保留缩小范围:
let g : object;
if (g instanceof Test) {
const gTest = g;
() => {
gTest.hello();
};
}
Ah'ol=this+1@ChrisW. 具有新用例的旧解决方案;)我认为这个答案要么部分不正确,要么已经过时。在TypeScript 3+中,类型保护可以跨越
const
声明变量的函数边界。将原始问题中的第9行更改为const g:object=new Test()代码>允许它无错误地编译。(可以理解的是,let
收缩不会跨越函数边界,因为变量可以在调用函数之前重新分配回对象
。@Miles不,问题仍然存在,特别是它与使用的箭头函数()=>
有关,我说的是const
:对我来说,这似乎缩小了跨越函数边界的范围。