Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: add function to momentjs' prototype

Tags:

typescript

I'm trying to add a function to the momentjs prototype. In Javascript, the code was like this:

Object.getPrototypeOf(moment()).isWeekend = function() {
    return this.isoWeekday() >= 6;
};

How do I do this in typescript? I've read that i need to duplicate the interface and and my function to it, but that's not working:

module moment {
    interface Moment {
        isWeekend(): boolean
    }

    Moment.prototype.isWeekend = () => {
        this.isoWeekday() >= 6;
    };
}
like image 678
Bart van den Burg Avatar asked Feb 14 '26 18:02

Bart van den Burg


1 Answers

You need to place the actual extension outside of the module, and you need to export the interface...

module moment {
    export interface Moment {
        isWeekend(): boolean
    }
}

(<any>moment).fn.isWeekend = function() {
    this.isoWeekday() >= 6;
};
like image 84
Fenton Avatar answered Feb 16 '26 09:02

Fenton



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!