【问题标题】:Using reserved keywords as methods on Classes/Instances in Typescript在 Typescript 中使用保留关键字作为类/实例的方法
【发布时间】:2013-12-09 03:40:29
【问题描述】:

如果我在 Typescript 类中使用保留关键字(例如 deletecontinue)作为方法名称,那么我会遇到 IE8 的问题。

例如:

class Foo {
    delete() : void {
        console.log('Delete called');
    }

    continue() : void {
        console.log('Continue called');
    }
}

生成以下 javascript:

var Foo = (function () {
    function Foo() {
    }
    Foo.prototype.delete = function () {
        console.log('Delete called');
    };

    Foo.prototype.continue = function () {
        console.log('Continue called');
    };
    return Foo;
})();

但是,这在 IE8 中运行不佳。 IE8 更愿意使用这个:

var Bar = (function () {
    function Bar() {
    }
    Bar.prototype['delete'] = function () {
        console.log('Delete called');
    };

    Bar.prototype['continue'] = function () {
        console.log('Continue called');
    };
    return Bar;
})();

有没有一种方法可以在保持我的代码 IE8 良好行为的同时保留 Typescript 的 Typed 优点?

在我的特殊情况下,我正在尝试编写一个实现 ng.IHttpService interface 的类,因此需要将 delete 作为实例方法。

【问题讨论】:

    标签: javascript internet-explorer-8 typescript


    【解决方案1】:
    class Foo {
        "delete"() : void {
            console.log('Delete called');
        }
    
        "continue"() : void {
            console.log('Continue called');
        }
    }
    

    翻译成

    var Foo = (function () {
        function Foo() {
        }
        Foo.prototype["delete"] = function () {
            console.log('Delete called');
        };
    
        Foo.prototype["continue"] = function () {
            console.log('Continue called');
        };
        return Foo;
    })();
    

    请注意,我从未使用过 TypeScript。我刚刚去了他们的网站,快速浏览了规范 PDF,发现可以使用字符串文字,并在 TypeScript 操场上进行了尝试。

    【讨论】:

    • 不错!我会测试它是否仍然正确地实现了接口。
    • 是的,这仍然满足implements ng.IHttpService 的要求。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-31
    • 1970-01-01
    • 2023-01-10
    • 2020-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多