【问题标题】:Typescript: Add a function to moment.js namespace打字稿:向 moment.js 命名空间添加一个函数
【发布时间】: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()

关于如何让它工作的任何建议?

【问题讨论】:

  • 因为myFuncmoment中不存在
  • 你应该导入你自己的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


【解决方案1】:

您可以使用 TypeScript 的 declaration merging 扩展 moment 以包含您的 myFunc

以下对我有用(使用 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

【讨论】:

  • 看起来不错。并且只是补充一点,如果你把它放在一个单独的 .ts 文件中 - 只需稍后导入文件。 import './file';
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-05
  • 1970-01-01
  • 2019-10-13
  • 1970-01-01
  • 2020-06-30
  • 2018-01-11
  • 2021-02-01
相关资源
最近更新 更多