TypeScript extend third party library moment.js

爱⌒轻易说出口 提交于 2020-02-03 09:48:09

问题


I simply want to add a function to the prototype of the Moment interface which will format always the same way whenever used. I tried already what can be found here.

declare module moment {
    export interface Moment {
        myFormat: () => string;
    }
}

And in some other file, the implementation:

Moment.prototype.myFormat = ():string => { return this.format("DD.MM.YYY"); }

However, this is not working. I simply want to be able to call moment(aDate).myFormat() but I don't get it to work.

Already tried using declare module "moment" and some variations of moment.Moment but still the same.

As found in the link there is no declare used. But then I get the error

'declare' modifier required for top level element.


回答1:


This is working

import moment from 'moment';
declare module 'moment' {
   export interface Moment {
     myFormat: () => string;
   }
 }
moment().myFormat(); 


来源:https://stackoverflow.com/questions/48227192/typescript-extend-third-party-library-moment-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!