我试图在momentjs原型中添加一个函数。在Javascript中,代码是这样的:
Object.getPrototypeOf(moment()).isWeekend = function() {
return this.isoWeekday() >= 6;
};
我如何在打字稿中这样做?我已经读过,我需要复制界面和我的功能,但这不起作用:
module moment {
interface Moment {
isWeekend(): boolean
}
Moment.prototype.isWeekend = () => {
this.isoWeekday() >= 6;
};
}
答案 0 :(得分:2)
您需要将实际扩展名放在模块外部,并且需要导出接口...
module moment {
export interface Moment {
isWeekend(): boolean
}
}
(<any>moment).fn.isWeekend = function() {
this.isoWeekday() >= 6;
};
答案 1 :(得分:0)
这对我有用。
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;
}
参考:
https://medium.com/my-life/extension-method-in-typescript-66d801488589