Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: Add a function to moment.js namespace

I'm trying to add extra functionality to moment.js library. I want to add a function that itself requires a moment() call in its body and I'm having a hard time figuring this out.

I'm using the latest version of Typescript and moment.js. I've tried to find a solution but I've come up with nothing. This solution (Typescript: add function to momentjs' prototype) has come close to working, I think, but still nothing.

So far what I have is:

import * as moment from 'moment';

export namespace moment{
    interface Moment{
        myFunc(): boolean;
    }
}

(moment as any).fn.myFunc = function() {
    return moment(....);
};

I'm not sure where I'm going wrong but when I try to use the moment library and myFunc I thought importing moment (import * as moment from 'moment') would be enough but myFunc isn't recognized, only the standard moment functions.

Ex. This says myFunc() isn't recognized.

import * as moment from 'moment'
import Moment = moment.Moment

... moment().add(...) //works
... moment().myFunc() // doesn't recognize myFunc()

Any suggestions on how to get this to work?

like image 530
J. Doe Avatar asked Jul 29 '26 04:07

J. Doe


1 Answers

You can extend moment to include your myFunc using TypeScript's declaration merging.

The following works for me (using TypeScript 2.4.2):

import * as moment from 'moment';

declare module "moment" {
  interface Moment {
    myFunc(): moment.Moment;
  }
}

(moment as any).fn.myFunc = function (): moment.Moment {
  console.log("Called myFunc!");
  return moment();
};

console.log(moment().myFunc().valueOf());

And outputs:

Called myFunc!
1501901308611
like image 154
cartant Avatar answered Jul 31 '26 16:07

cartant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!