Typescript:将函数添加到momentjs';原型
我正在尝试向momentjs原型添加一个函数。在Javascript中,代码如下所示:Typescript:将函数添加到momentjs';原型,typescript,Typescript,我正在尝试向momentjs原型添加一个函数。在Javascript中,代码如下所示: Object.getPrototypeOf(moment()).isWeekend = function() { return this.isoWeekday() >= 6; }; 如何在typescript中执行此操作?我已经读到,我需要将接口和功能复制到它,但这不起作用: module moment { interface Moment { isWeekend():
Object.getPrototypeOf(moment()).isWeekend = function() {
return this.isoWeekday() >= 6;
};
如何在typescript中执行此操作?我已经读到,我需要将接口和功能复制到它,但这不起作用:
module moment {
interface Moment {
isWeekend(): boolean
}
Moment.prototype.isWeekend = () => {
this.isoWeekday() >= 6;
};
}
您需要将实际扩展放置在模块外部,并且需要导出接口
module moment {
export interface Moment {
isWeekend(): boolean
}
}
(<any>moment).fn.isWeekend = function() {
this.isoWeekday() >= 6;
};
模块力矩{
输出接口力矩{
isWeekend():布尔值
}
}
(矩).fn.isWeekend=函数(){
this.isoWeekday()>=6;
};
它对我有用
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;
}
参考:
我已经尝试应用这个,但是当我尝试使用它时,我得到了“moment.isWeekend是未定义的”,看起来MomentJS没有扩展原型,而是添加到
fn
属性。我已经更新了示例。您还需要使用一个函数,而不是箭头函数,否则会影响此
的范围。我的错误是,我不必更改原始JavaScript代码,只需添加TypeScript声明即可。@Fenton我得到错误:[ts]无法将“矩”命名空间用作值。