【问题标题】:TypeScript extend third party library moment.jsTypeScript 扩展第三方库 moment.js
【发布时间】:2018-06-21 23:18:07
【问题描述】:

我只是想在Moment 接口的原型中添加一个函数,该函数在使用时将始终以相同的方式格式化。 我已经尝试过这里可以找到的内容。

declare module moment {
    export interface Moment {
        myFormat: () => string;
    }
}

在其他文件中,实现:

Moment.prototype.myFormat = ():string => { return this.format("DD.MM.YYY"); }

但是,这不起作用。我只是想能够打电话给moment(aDate).myFormat(),但我无法正常工作。

已经尝试使用declare module "moment"moment.Moment 的一些变体,但还是一样。

在链接中发现没有使用declare。但后来我得到了错误

顶级元素需要'declare'修饰符。

【问题讨论】:

  • 当您将时刻导入文件时,您是在导入时刻还是您的文件?例如import * as moment from 'moment'import * as moment from '[yourversion]'?

标签: javascript typescript momentjs typescript-typings


【解决方案1】:

这是有效的

import moment from 'moment';
declare module 'moment' {
   export interface Moment {
     myFormat: () => string;
   }
 }
moment().myFormat(); 

【讨论】:

    猜你喜欢
    • 2018-03-11
    • 2018-01-12
    • 2017-06-22
    • 1970-01-01
    • 2021-11-13
    • 2018-09-10
    • 2021-03-17
    • 2017-08-06
    • 1970-01-01
    相关资源
    最近更新 更多