【发布时间】:2017-08-04 19:59:32
【问题描述】:
我正在尝试向 moment.js 库添加额外的功能。我想添加一个本身需要在其主体中调用 moment() 的函数,但我很难弄清楚这一点。
我正在使用最新版本的 Typescript 和 moment.js。我试图找到解决方案,但我一无所获。我认为这个解决方案 (Typescript: add function to momentjs' prototype) 已经接近工作了,但仍然没有。
到目前为止,我拥有的是:
import * as moment from 'moment';
export namespace moment{
interface Moment{
myFunc(): boolean;
}
}
(moment as any).fn.myFunc = function() {
return moment(....);
};
我不确定哪里出错了,但是当我尝试使用 moment 库和 myFunc 时,我认为导入 moment (import * as moment from 'moment') 就足够了,但 myFunc 无法识别,只有标准矩函数。
例如。这表示 myFunc() 无法识别。
import * as moment from 'moment'
import Moment = moment.Moment
... moment().add(...) //works
... moment().myFunc() // doesn't recognize myFunc()
关于如何让它工作的任何建议?
【问题讨论】:
-
因为
myFunc在moment中不存在 -
你应该导入你自己的
moment类型,而不是moment导出的类型。所以把import * as moment from 'moment'改成import * as moment from './moment-extended'什么的。 -
好的,所以我将代码更改为@csander 建议的方式,但它不起作用。我这样做对吗?我在上面的示例中导入
* as moment from 'moment'和* as myMoment from './moment.extended并尝试像这样调用myFunc:'myMoment.myFunc()' 但我收到此错误:Property 'myFunc' does not exist on type 'typeof "c:/ Git/.../moment.extended"'
标签: javascript angular typescript momentjs