【问题标题】:Extending an interface in TypeScript在 TypeScript 中扩展接口
【发布时间】:2016-07-06 02:53:27
【问题描述】:

在 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。

【问题讨论】:

    标签: javascript interface typescript


    【解决方案1】:

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

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

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

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

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

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

    【讨论】:

    • 赞成。在我看来,这比弄乱内置对象的原型要好,即使 JS 让你这样做。
    【解决方案2】:

    你可以这样:

    interface Date
    {
        Minimum(): Date;
    }
    
    (<any>Date.prototype).Minimum = function () { return (new Date()); }
    
    let d = new Date();
    console.log(d.Minimum());
    

    希望这会有所帮助。

    【讨论】:

    • 请注意,any 的断言不是必需的。
    猜你喜欢
    • 2020-10-30
    • 2020-06-09
    • 2017-10-21
    • 2020-04-09
    • 2018-06-20
    • 2018-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多