Search code examples
typescriptmomentjsprototype

Adding a function to type Duration under momentjs in TS


Can't add a function to Duration interface under momentjs package

I'm trying to get the months by a round of 30 days (version 2.24.0 return 0.94~ month for 30 days and I need it to be one)

for some reason i cant do this:

        Duration.getRealMonths = function () {
          return Math.floor(this.as('days')/30);
        }

Here's a stack blitz: https://stackblitz.com/edit/angular-moment-example-6kknck

I expect this:

let duration: Duration = moment.duration(30,'days');

to return 1 for example


Solution

  • I assume you have imported the type Duration. Use moment.duration instead which should be of type Duration.

    Another problem is that your function getRealMonths does not exists on Duration, so you can't simply add it.