【问题标题】:How to extends basic type with typescript如何使用打字稿扩展基本类型
【发布时间】: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


【解决方案1】:

更改你的接口名称,它与javascript的默认类型Date重复

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

【讨论】:

  • 谢谢,但不是更好:同样的问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-11
  • 1970-01-01
  • 2022-01-26
  • 2018-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多