Rod*_*ddy 5 typescript typeguards
这不应该正确编译吗?我"Property 'hello' does not exist on type 'object'.在突出显示的行中收到错误“。
我可以g.hello毫无问题地访问胖箭头功能之外。
class Test {
constructor() {
}
hello() : string {
return "Hello";
}
}
let g : object;
if (g instanceof Test) {
() => {
g.hello(); ////// ERROR HERE /////
};
}
Run Code Online (Sandbox Code Playgroud)
类型保护对变量(或其他任何东西)所做的缩小不会跨越函数边界。这是设计限制。
解决此问题的一种方法是分配g给一个新变量,该变量将根据缩小范围推断其类型。访问箭头函数中的新变量将按预期工作:
class Test {
constructor() {
}
hello() : string {
return "Hello";
}
}
let g : object;
if (g instanceof Test) {
const gTest = g;
() => {
gTest.hello();
};
}
Run Code Online (Sandbox Code Playgroud)
g如果不改变,解决此问题的另一种方法是g使用进行声明const。这将使编译器保留缩小范围:
let g : object;
if (g instanceof Test) {
const gTest = g;
() => {
gTest.hello();
};
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
294 次 |
| 最近记录: |