【问题标题】:Angular8: Prototype Inheritence with Date ObjectAngular 8:带有日期对象的原型继承
【发布时间】:2020-04-21 11:05:44
【问题描述】:

我试图找到一种在 Angular(Typescript) 中向 Date 原型添加一些方法的方法,并通过 GitHub 找到了下面的解决方案,效果很好。

date.extensions.ts

export {}

// DATE EXTENSIONS
// ================

declare global {
   interface Date {
      addDays(days: number, useThis?: boolean): Date;
      isToday(): boolean;
      clone(): Date;
      isAnotherMonth(date: Date): boolean;
      isWeekend(): boolean;
      isSameDate(date: Date): boolean;
   }
}

Date.prototype.addDays = (days: number): Date => {
   if (!days) return this;
   console.log(this);
   let date = this;
   date.setDate(date.getDate() + days);

   return date;
};

Date.prototype.isToday = (): boolean => {
   let today = new Date();
   return this.isSameDate(today);
};

Date.prototype.clone = (): Date => {
   return new Date(+this);
};

Date.prototype.isAnotherMonth = (date: Date): boolean => {
   return date && this.getMonth() !== date.getMonth();
};

Date.prototype.isWeekend = (): boolean => {
   return this.getDay() === 0 || this.getDay() === 6;
};

Date.prototype.isSameDate = (date: Date): boolean => {
   return date && this.getFullYear() === date.getFullYear() && this.getMonth() === date.getMonth() && this.getDate() === date.getDate();
};

参考:https://github.com/Microsoft/TypeScript/issues/7726#issuecomment-234469961

问题:谁能告诉我为什么export {}写在TS文件的开头,为什么要在这里添加?

【问题讨论】:

    标签: javascript angular typescript date


    【解决方案1】:

    如果不从date.extensions.ts 导出任何内容,该文件将不会考虑模块 你会遇到三个错误

    error TS2669: Augmentations for the global scope can only be directly nested in external modules or ambient module declarations.
    
    error TS2306: File 'date.extensions.ts' is not a module.
    
    and an error about the Date type 
    

    只需 export {} 用于将 filw 作为模块,因为有导出的东西

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-27
      • 2013-10-02
      • 1970-01-01
      • 2012-06-19
      • 1970-01-01
      • 1970-01-01
      • 2011-01-27
      相关资源
      最近更新 更多