Javascript 在 TypeScript 中扩展功能
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13897659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Extending functionality in TypeScript
提问by Matthew Layton
Possible Duplicate:
How does prototype extend on typescript?
可能的重复:
原型如何在打字稿上扩展?
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:
我目前正在学习 TypeScript,想知道如何向现有对象添加功能。假设我想将 Foo 的实现添加到 String 对象。在 JavaScript 中,我会这样做:
String.prototype.Foo = function() {
// DO THIS...
}
Understanding that TypeScript classes, interfaces and modules are open ended led me to try the following, without success
了解 TypeScript 类、接口和模块是开放式的,这让我尝试了以下方法,但没有成功
1. Reference the JavaScript implementation from TypeScript
1. 从 TypeScript 中引用 JavaScript 实现
JavaScript:
String.prototype.Foo = function() {
// DO THIS...
}
TypeScript:
var x = "Hello World";
x.Foo(); //ERROR, Method does not exist
2. Extend the interface
2.扩展接口
interface String {
Foo(): number;
}
var x = "Hello World";
x.Foo(); //Exists but no implementation.
3. Extend the class
3. 扩展类
class String {
Foo(): number {
return 0;
}
}
// ERROR: Duplicate identifier '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?
从这些结果中可以看出,到目前为止,我已经能够通过接口契约添加该方法,但没有实现,那么,我该如何定义和实现我的 Foo 方法作为预先存在的 String 类的一部分?
回答by Matthew Layton
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.
我找到了解决办法。它结合了接口和 JavaScript 实现。该接口提供了 TypeScript 的契约,允许新方法的可见性。JavaScript 实现提供将在调用方法时执行的代码。
Example:
例子:
interface String {
foo(): number;
}
String.prototype.foo= function() {
return 0;
}
As of TypeScript 1.4 you can now also extend static members:
从 TypeScript 1.4 开始,您现在还可以扩展静态成员:
interface StringConstructor {
bar(msg: string): void;
}
String.bar = function(msg: string) {
console.log("Example of static extension: " + msg);
}

