Reputation: 2364
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;
};
}
Upvotes: 3
Views: 2814
Reputation: 166
It's working for me.
import * as moment from 'moment';
declare module 'moment' {
export interface Moment {
toTaiwaneseYear(): number;
}
}
(moment.fn as any).toTaiwaneseYear = function () {
const _self = this as moment.Moment;
return _self.year() - 1911;
}
reference:
https://medium.com/my-life/extension-method-in-typescript-66d801488589
Upvotes: 1
Reputation: 251102
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;
};
Upvotes: 2