如何在打字稿中使用静态方法扩展和输入导入的类

Eri*_*rth 1 class typescript luxon

我正在尝试使用静态方法扩展 Luxon DateTime 类,如下所示:

DateTime.fromDob = function(dob: number | string | DateTime) {
  if (dob instanceof DateTime) {
    return dob
  }
  if (dob && (typeof dob === 'number' || typeof dob === 'string')) {
    return DateTime.fromFormat(String(dob), DOB)
  }
  return null
}
Run Code Online (Sandbox Code Playgroud)

打字稿错误:Property 'isInFuture' does not exist on type 'typeof DateTime'.ts(2339)

我尝试将该方法添加到 d.ts 文件中的模块声明中,但无济于事:

declare module 'luxon/src/datetime' {
  export interface DateTime  {
    public static fromDob(dob: number | string | DateTime): DateTime | null
  }
}
Run Code Online (Sandbox Code Playgroud)

但这并不能解决错误。

Tel*_*bov 5

我认为static打字稿接口中不允许使用修饰符。

作为解决方法,您可以尝试使用namespace

一个例子:

declare module 'luxon/src/datetime' {
  namespace DateTime {
    export function fromDob(dob: number | string | DateTime): DateTime | null;
  }
}

DateTime.fromDob = function() {
  console.log('fromDob');
};
DateTime.fromDob();
Run Code Online (Sandbox Code Playgroud)