moment-duration-format.d.ts定义不扩展矩量模块

Jas*_*ndo 6 javascript momentjs typescript

知道为什么这不起作用或如何扩展持续时间接口以支持格式功能?

declare module 'moment' {
     interface Duration {
       format(template: string, precision?: string, settings?: any): string;
     }

}
Run Code Online (Sandbox Code Playgroud)

当用作:

moment.duration(minutes, 'minutes').format('mm');
Run Code Online (Sandbox Code Playgroud)

我收到"持续时间"类型中"格式"不存在的错误

fxl*_*ire 8

进口:

import * as moment from 'moment';
import 'moment-duration-format';
Run Code Online (Sandbox Code Playgroud)

在您的课程之外,定义接口:

interface Duration extends moment.Duration {
  format: (template?: string, precision?: number, settings?: DurationSettings) => string;
}

interface DurationSettings {
  forceLength: boolean;
  precision: number;
  template: string;
  trim: boolean | 'left' | 'right';
}
Run Code Online (Sandbox Code Playgroud)

然后在你的代码中:

const duration = moment.duration(minutes, 'minutes') as Duration;
return duration.format('mm');
Run Code Online (Sandbox Code Playgroud)

如果您Duration在另一个文件中定义了界面,则还需要导出和导入它.


小智 8

首先,安装类型:

npm install --save-dev @types/moment-duration-format
Run Code Online (Sandbox Code Playgroud)

其次,将它们导入您的文件:

/// <reference path='../..your-path.../node_modules/@types/moment-duration-format/index.d.ts' />
import * as moment from 'moment';
import 'moment-duration-format';
Run Code Online (Sandbox Code Playgroud)

然后你可以使用

moment.duration(minutes, 'minutes').format('mm');
Run Code Online (Sandbox Code Playgroud)