【发布时间】:2020-03-27 11:06:00
【问题描述】:
我正在尝试扩展 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
}
});
但是当我想使用它时:
“日期”类型上不存在属性“toDateTime”
我在这里错过了什么?
我使用 vuejs,所以也许我可以将它声明为全局或其他什么?
【问题讨论】:
-
扩展全局会更有意义,因为您确实扩展了全局。请注意,为了本地目的而污染全局范围是一种不好的做法。
标签: typescript vue.js