我正在使用 TypeScript 和一个名为 'moment-transform' 的 moment.js 插件.
moment-transform 动态地将 transform
函数添加到 moment 对象。用法是这样的:
import moment = require('moment');
require('moment-transform'); // simply adds transform function
moment().transform('YYYY-MM-+07 00:00:00.000').toDate();
但是,当使用 TypeScript 构建此代码时,我收到此错误:
error TS2339: Property 'transform' does not exist on type 'Moment'.
如何正确处理动态添加的函数?
[edit] (moment() as any).transform('YYYY-MM-+07 00:00:00.000').toDate();
似乎有效。这真的是要走的路吗?是否有可能在全局范围内指定这一点?
最佳答案
您可以使用以下方法扩展moment
定义:
在自定义“moment.d.ts”中声明 moment
的任何扩展:
import * as moment from "moment";
declare module "moment"
{
interface Moment
{
transform(a: string): Moment;
}
}
并在您的“my.ts”中使用它:
import * as moment from 'moment';
moment().transform('qw').toDate();
有关此事的更多信息:Module Augmentation
关于javascript - TypeScript 和带有动态添加功能的矩变换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42754343/