[英]Typescript Type Guards and fat arrow function
这不应该正确编译吗? 我在突出显示的行中收到错误"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 /////
};
}
这不应该正确编译吗? 我在高亮显示的行中收到错误消息"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 /////
};
}
class Test {
constructor() {
}
hello() : string {
return "Hello";
}
}
declare let g : object;
if (g instanceof Test) {
() => {
g.hello(); // error
};
}
g
是定义函数时的Test
,但函数运行时g
可能不是Test
。
class Test {
constructor() {
}
hello() : string {
return "Hello";
}
}
declare const g : object;
if (g instanceof Test) {
() => {
g.hello(); // ok
};
}
g
是不可变的,在定义函数之后g
始终是一个Test
。
class Test {
constructor() {
}
hello() : string {
return "Hello";
}
}
declare const g : object;
if (g instanceof Test) {
function f() {
g.hello(); // error
};
}
在底层实现中,常规函数f
由 ES5 var
定义,而不是 ES6 let
。 当g
可能不是Test
时,变量提升提升f
声明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.