如何使用打字稿扩展基本类型

时间:2020-03-27 11:06:00

标签: typescript vue.js

我正在尝试扩展Date类型,以便在整个应用程序中轻松重用。

问题:这不行,我也不明白为什么。 我们走了。

我在date.ts中的声明:( ressources var是一个i18n文件)

export interface Date {
    toDate: (locale: string) => string;
    toTime: (locale: string) => string;
    toDateTime: (locale: string, useText?: boolean) => string;
}

Object.defineProperties(Date.prototype, {
    toDate: {
        value: function (locale: string) {
            return this.toLocaleDateString(locale, { day: "2-digit", month: "2-digit", year: "numeric" });
        },
        configurable: true,
        writable: true
    },
    toTime: {
        value: function (locale: string) {
            return this.toLocaleDateString(locale, { hour: "2-digit", minute: "2-digit" }).substring(0, 5);
        },
        configurable: true,
        writable: true
    },
    toDateTime: {
        value: function (locale: string, useText: boolean = false) {
            return useText
                ? `${ressources.message.events.the} ${this.toDate(locale)} ${ressources.message.events.at} ${this.toTime(locale)}`
                : `${this.toDate(locale)} ${this.toTime(locale)}`;
        },
        configurable: true,
        writable: true
    }
});

但是当我想使用它时:

enter image description here

类型为“日期”的属性“ toDateTime”不存在

我在这里想念什么?

我使用vuejs,所以也许可以将其声明为全局或其他内容?

1 个答案:

答案 0 :(得分:0)

更改界面名称,该名称与javascript的默认类型Date相同

export interface Date { // something else, maybe myDate
    toDate: (locale: string) => string;
    toTime: (locale: string) => string;
    toDateTime: (locale: string, useText?: boolean) => string;
}