在TypeScript中扩展功能 [英] Extending functionality in TypeScript

查看:562
本文介绍了在TypeScript中扩展功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

原型如何在打字稿上扩展?

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

I am currently learning TypeScript, and would like to know how it is possible to add functionality to existing objects. Say I want to add an implementation for Foo to the String object. In JavaScript I would do this:

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

了解TypeScript类,接口和模块是开放式的导致我尝试以下操作,但没有成功

Understanding that TypeScript classes, interfaces and modules are open ended led me to try the following, without success

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方法作为预先存在的String类?

As you can see from these results, so far I have been able to add the method via an interface contract, but no implementation, so, how do I go about defining AND implementing my Foo method as part of the pre-existing String class?

推荐答案

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

I have found the solution. It takes a combination of the interface and the JavaScript implementation. The interface provides the contract for TypeScript, allowing visibility of the new method. The JavaScript implementation provides the code that will be executed when the method is called.

示例:

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中扩展功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆