在 TypeScript 中扩展接口
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36099843/
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 an interface in TypeScript
提问by Raheel Khan
In JavaScript, it is straight-forwardd to add functions and members to the prototype
of any type. I'm trying to achieve the same in TypeScript as follows:
在 JavaScript 中,可以直接向prototype
任何类型的 中添加函数和成员。我正在尝试在 TypeScript 中实现相同的目标,如下所示:
interface Date
{
Minimum: Date;
}
Date.prototype.Minimum = function () { return (new Date()); }
This produces the following error:
这会产生以下错误:
Type '() => Date' is not assignable to type 'Date'.
Property 'toDateString' is missing in type '() => Date'.
Considering TS is strongly-types, how could we achieve this?
考虑到 TS 是强类型,我们如何实现这一点?
Since I'm writing a custom utility library in TS, I'd rather not resort to JS.
由于我正在 TS 中编写自定义实用程序库,因此我不想求助于 JS。
采纳答案by Amid
You can have it like this:
你可以这样:
interface Date
{
Minimum(): Date;
}
(<any>Date.prototype).Minimum = function () { return (new Date()); }
let d = new Date();
console.log(d.Minimum());
Hope this helps.
希望这可以帮助。
回答by obe
Interfaces don't get transpiled to JS, they're just there for defining types.
接口不会被转换为 JS,它们只是用于定义类型。
You could create a new interface that would inherit from the first:
您可以创建一个从第一个继承的新接口:
interface IExtendedDate extends Date {
Minimum: () => Date;
}
But for the actual implementations you will need to define a class. For example:
但是对于实际的实现,你需要定义一个类。例如:
class ExtendedDate implements IExtendedDate {
public Minimum(): Date {
return (new ExtendedDate());
}
}
However note that you can do all this without an interface.
但是请注意,您可以在没有界面的情况下完成所有这些。