【问题标题】:Extending functionality in TypeScript [duplicate]在 TypeScript 中扩展功能 [重复]
【发布时间】:2012-12-03 13:47:49
【问题描述】:

可能重复:
How does prototype extend on typescript?

我目前正在学习 TypeScript,想知道如何为现有对象添加功能。假设我想将 Foo 的实现添加到 String 对象。在 JavaScript 中我会这样做:

String.prototype.Foo = function() {
    // DO THIS...
}

了解 TypeScript 类、接口和模块是开放式的,这让我尝试了以下方法,但没有成功

1.从 TypeScript 引用 JavaScript 实现

    JavaScript:

    String.prototype.Foo = function() {
        // DO THIS...
    }

    TypeScript:

    var x = "Hello World";
    x.Foo(); //ERROR, Method does not exist

2.扩展接口

interface String {
    Foo(): number;
}

var x = "Hello World";
x.Foo(); //Exists but no implementation.

3.扩展类

class String {
    Foo(): number {
        return 0;
    }
}

// ERROR: Duplicate identifier 'String'

正如您从这些结果中看到的,到目前为止,我已经能够通过接口契约添加方法,但没有实现,那么,我该如何定义和实现我的 Foo 方法作为预先存在的一部分字符串类?

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    我找到了解决方案。它结合了接口和 JavaScript 实现。该接口为 TypeScript 提供合约,允许新方法的可见性。 JavaScript 实现提供了调用方法时将执行的代码。

    示例:

    interface String {
        foo(): number;
    }
    
    String.prototype.foo= function() {
        return 0;
    }
    

    从 TypeScript 1.4 开始,您现在还可以扩展静态成员:

    interface StringConstructor {
        bar(msg: string): void;
    }
    
    String.bar = function(msg: string) {
        console.log("Example of static extension: " + msg);
    }
    

    【讨论】:

    • 没错,这就是它的本意。请记住,TypeScript 本身并不是一门语言,它只是一种语法糖。因此,以“JavaScript 风格”编写内容是一种没有任何缺点的好习惯。
    • 这个解决方案真的适用于 String 吗?因为我正在做 exact 相同的事情并得到该属性在 String 类型上不存在的编译错误。我错过了什么? (使用 tsc 1.4.1)
    • @OlegMihailik 所有语言不只是语法糖吗?
    • @series0ne,如果复制上面的代码,[ts] Property 'foo' does not exist on type 'String'.
    • 以防其他人遇到与我相同的问题:我在这里使用了代码,发现它有效。但是,如果我在模块中使用它(即使用 export 语句),那么我会收到错误 [ts] Property 'foo' does not exist on type 'String'.(在 VS Code 和操场上)。解决方法是使接口全局化:declare global { interface String { foo(): number; } }
    猜你喜欢
    • 2020-10-12
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 2021-11-20
    • 2021-11-06
    相关资源
    最近更新 更多