繁体   English   中英

Typescript 类型保护和粗箭头功能

[英]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 /////
    };
}

let + 箭头函数

class Test {
    constructor() {
    }
    hello() : string {
        return "Hello";
    }
}

declare let g : object;

if (g instanceof Test) {
    () => {
        g.hello(); // error
    };
}

g是定义函数时的Test ,但函数运行时g可能不是Test

const + 箭头函数

class Test {
    constructor() {
    }
    hello() : string {
        return "Hello";
    }
}

declare const g : object;

if (g instanceof Test) {
    () => {
        g.hello(); // ok
    };
}

g是不可变的,在定义函数之后g始终是一个Test

const + 正则函数

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM