3

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;
    };
}

2 Answers 2

2

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;
};
Sign up to request clarification or add additional context in comments.

4 Comments

I've tried to apply this, but i get "moment.isWeekend is undefined" when I try to use it
It looks like with MomentJS you don't extend the prototype, but instead add to a fn property. I have updated the example. You also need to use a function, not an arrow-function as otherwise you will affect the scope of this.
My mistake was that I didn't have to change the original JavaScript code, just add the TypeScript declaration.
@Fenton I get the error: [ts] cannot use 'moment' namespace as a value.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.