在TypeScript中扩展接口

时间:2016-03-19 09:02:46

标签: javascript interface 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。

2 个答案:

答案 0 :(得分:17)

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

您可以创建一个从第一个继承的新界面:

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

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

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

但请注意,您可以在没有界面的情况下完成所有这些操作。

答案 1 :(得分:1)

你可以这样:

interface Date
{
    Minimum(): Date;
}

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

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

希望这有帮助。

相关问题