首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular8: Date对象的原型继承

Angular8: Date对象的原型继承
EN

Stack Overflow用户
提问于 2020-01-03 03:48:58
回答 1查看 43关注 0票数 1

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

date.extensions.ts

代码语言:javascript
复制
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文件的开头,为什么有必要在这里添加?

EN

回答 1

Stack Overflow用户

发布于 2020-01-03 05:18:33

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

代码语言:javascript
复制
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 {}将文件作为模块使用,因为它已经导出了一些东西

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59569164

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档