how to extend and type imported class with static method in typescript

Viewed 26

I'm trying to extend the Luxon DateTime class with static methods like so:

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
}

typescript errors on: Property 'isInFuture' does not exist on type 'typeof DateTime'.ts(2339)

I have tried adding the method to the module declaration in my d.ts file but to no avail:

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

but this doesn't fix the error.

1 Answers

I think static modifier is not allowed in typescript interfaces.

As a workaround you could try to use namespace instead.

An example:

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

DateTime.fromDob = function() {
  console.log('fromDob');
};
DateTime.fromDob();
Related