繁体   English   中英

在TypeScript中扩展接口

[英]Extending an interface in TypeScript

在JavaScript中,可以直接将函数和成员添加到任何类型的prototype中。 我试图在TypeScript中实现相同的目的如下:

interface Date
{
    Minimum: Date;
}

Date.prototype.Minimum = function () { return (new Date()); }

这会产生以下错误:

Type '() => Date' is not assignable to type 'Date'.
Property 'toDateString' is missing in type '() => Date'.

考虑到TS是强类型的,我们怎么能实现这个目标呢?

由于我在TS中编写自定义实用程序库,所以我宁愿不使用JS。

接口不会被转换为JS,它们只是用于定义类型。

您可以创建一个从第一个继承的新接口:

interface IExtendedDate extends Date {
    Minimum: () => Date;
}

但是对于实际的实现,您需要定义一个 例如:

class ExtendedDate implements IExtendedDate {
    public Minimum(): Date {
        return (new ExtendedDate());
    }
}

但请注意,您可以在没有界面的情况下执行所有操作。

你可以这样:

interface Date
{
    Minimum(): Date;
}

(<any>Date.prototype).Minimum = function () { return (new Date()); }

let d = new Date();
console.log(d.Minimum());

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM