【问题标题】:TypeScript Extend Prototype not working when import other extend prototype导入其他扩展原型时,TypeScript 扩展原型不起作用
【发布时间】:2020-09-22 16:31:33
【问题描述】:

对不起,我有一个字符串和日期扩展名,一切正常,直到我想在我的日期扩展名中使用我的字符串扩展名的属性,我已经搜索过,但我在论坛中没有找到任何东西,是否发生过有人吗?

============================================

import './string.extension';

type IntervalDateDiff = 'days' | 'months' | 'years' | 'hours' | 'minutes';

interface Date {
    dateDiff(dateStart: Date, intervalo: IntervalDateDiff): number,
    format(): string,
    formatTime(): string,
    onlyDate(): Date,
    newDate(date: string): Date
}

Date.prototype.dateDiff = function (dateStart: Date, intervalo: IntervalDateDiff): number {
    const dateEnd: Date = this;
    const miliseconds = dateEnd.getTime() - dateStart.getTime();

    let intervaloTiempo = 0;
    switch (intervalo) {
        case 'minutes':
            intervaloTiempo = 1000*60;
            break;
        case 'hours':
            intervaloTiempo = 1000*60*60;
            break;
        case 'days':
            intervaloTiempo = 1000*60*60*24;
            break;
        case 'months':
            intervaloTiempo = 1000*60*60*30.417;
            break;
        case 'years':
            intervaloTiempo = 1000*60*60*30.417*12;
            break;
    }

    return miliseconds / intervaloTiempo;
}

Date.prototype.newDate = function (date: string): Date {
    date = date.left(10);
    
    const year = +(date.left(4));
    const month = +(date.substring(6, 2));
    const day = +(date.right(2));

    return new Date(year, month + 1, day);
}

错误如下: “日期”类型上不存在属性“日期差异”。 “日期”类型上不存在属性“newDate”。

【问题讨论】:

    标签: typescript prototype


    【解决方案1】:

    如果你想修改一个全局可用的类型,你需要把这些添加到declare global {} 块中。

    declare global {
      interface Date {
        dateDiff(dateStart: Date, intervalo: IntervalDateDiff): number,
        format(): string,
        formatTime(): string,
        onlyDate(): Date,
        newDate(date: string): Date
      }
    }
    

    这是必需的,因为默认情况下,类型在声明它们的文件中是本地的。但是您正在修改全局可用的对象,因此 typescript 需要知道您的意思是修改全局值,并且您知道更改预计在全球范围内。

    通过此更改,typescript 将允许您扩展全局对象的原型。

    Playground

    【讨论】:

      猜你喜欢
      • 2021-01-27
      • 2016-10-23
      • 2017-03-04
      • 1970-01-01
      • 2014-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多