猴子补丁打字稿日期构造函数有可能吗?

时间:2019-05-27 07:20:51

标签: typescript date monkeypatching

我想用打字稿修补内置的Date构造函数,因此当我调用UserManager时,可以定义返回的日期实际是什么。

我尝试着从这个问题开始:Date constructor monkey patch 但在打字稿中,您需要为日期构造函数提供属性:(类型'()=> any'缺少类型'DateConstructor'中的以下属性:parse,UTC,现在),您不能只为简单的功能。

有没有办法做到这一点? 谢谢

2 个答案:

答案 0 :(得分:1)

我不确定这里是否可以真正重写类型,但是您始终可以向Date对象添加所需的属性/方法:

interface Date {
  myExtraProperty: string
}

new Date().myExtraProperty; // works

答案 1 :(得分:1)

您将必须使用函数构造函数,否则对Date()的调用将引发:

const VanillaDate = Date;

declare global {
  interface DateConstructor {
    new(...args: number[]): Date;
  }
}

/** Monkey patches Date to where calls to Date.now() and new Date() will return another Date.  */
export function timeTravelTo(dateFactory: () => Date): void {
  timeTravelToNow();
  monkeyPatchDate(dateFactory());
}

export function timeTravelToNow(): void {
  Date = VanillaDate;
}

function monkeyPatchDate(date: Date): void {
  const newDate = function(...args: number[]) {
    if (args.length > 0) {
      return new VanillaDate(...args);
    }
    return new.target ? date : date.toString();
  };

  newDate.now = () => date.getTime();
  newDate.UTC = VanillaDate.UTC;
  newDate.parse = VanillaDate.parse;
  newDate.prototype = VanillaDate.prototype;

  Date = newDate as any;
}

相关问题