打字稿:向moment.js命名空间添加一个函数 [英] Typescript: Add a function to moment.js namespace
问题描述
我正在尝试向moment.js库添加额外的功能.我想添加一个函数,该函数本身在其主体中需要一个moment()调用,因此很难解决这个问题.
I'm trying to add extra functionality to moment.js library. I want to add a function that itself requires a moment() call in its body and I'm having a hard time figuring this out.
我正在使用最新版本的Typescript和moment.js.我试图找到一种解决方案,但是我什么也没想出来.我认为,这种解决方案( Typescript:将功能添加到momentjs的原型)已经接近有效,但仍然没有效果.
I'm using the latest version of Typescript and moment.js. I've tried to find a solution but I've come up with nothing. This solution (Typescript: add function to momentjs' prototype) has come close to working, I think, but still nothing.
到目前为止,我所拥有的是:
So far what I have is:
import * as moment from 'moment';
export namespace moment{
interface Moment{
myFunc(): boolean;
}
}
(moment as any).fn.myFunc = function() {
return moment(....);
};
我不确定我要去哪里,但是当我尝试使用moment库和myFunc时,我想导入一下矩(import *作为'moment'的矩)就足够了,但是myFunc不能被识别,仅标准力矩函数.
I'm not sure where I'm going wrong but when I try to use the moment library and myFunc I thought importing moment (import * as moment from 'moment') would be enough but myFunc isn't recognized, only the standard moment functions.
例如这表示无法识别myFunc().
Ex. This says myFunc() isn't recognized.
import * as moment from 'moment'
import Moment = moment.Moment
... moment().add(...) //works
... moment().myFunc() // doesn't recognize myFunc()
关于如何使其正常工作的任何建议?
Any suggestions on how to get this to work?
推荐答案
You can extend moment
to include your myFunc
using TypeScript's declaration merging.
以下对我有用(使用TypeScript 2.4.2):
The following works for me (using TypeScript 2.4.2):
import * as moment from 'moment';
declare module "moment" {
interface Moment {
myFunc(): moment.Moment;
}
}
(moment as any).fn.myFunc = function (): moment.Moment {
console.log("Called myFunc!");
return moment();
};
console.log(moment().myFunc().valueOf());
并输出:
Called myFunc!
1501901308611
这篇关于打字稿:向moment.js命名空间添加一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!