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

qc6wkl3g  于 2023-01-06  发布在  TypeScript
关注(0)|答案(4)|浏览(108)

你知道为什么这不起作用吗?或者我怎样才能扩展duration接口来支持format函数?

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

}

当用作:

moment.duration(minutes, 'minutes').format('mm');

我收到类型“Duration”上不存在“format”的错误

hujrc8aj

hujrc8aj1#

首先,安装类型:

npm install --save-dev @types/moment-duration-format

其次,将它们导入文件:

/// <reference path='../..your-path.../node_modules/@types/moment-duration-format/index.d.ts' />
import * as moment from 'moment';
import 'moment-duration-format';

然后您可以使用

moment.duration(minutes, 'minutes').format('mm');
v09wglhw

v09wglhw2#

进口:

import * as moment from 'moment';
import 'moment-duration-format';

在类外部定义接口:

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';
}

然后在代码中:

const duration = moment.duration(minutes, 'minutes') as Duration;
return duration.format('mm');

如果在另一个文件中定义了Duration接口,则还需要导出和导入它。

wqnecbli

wqnecbli3#

您需要安装以下依赖项:

"dependencies": {
  "@types/moment-duration-format": "2.2.2",
  "moment": "2.24.0",
  "moment-duration-format": "2.3.2"
}

如果是这种情况,那么你需要这些导入完全相同的顺序:

import * as moment from 'moment';
import 'moment-duration-format';

之后,您应该能够执行以下操作:

const seconds: number = Math.floor(process.uptime());
const formatted: string = moment.duration(seconds, 'seconds').format({
  precision: 0,
  template: 'y [years], w [weeks], d [days], h [hours], m [minutes], s [seconds]',
});
jmo0nnb3

jmo0nnb34#

应该使用namespace而不是module

declare namespace moment {
     interface Duration {
       format(template: string, precision?: string, settings?: DurationSettings): string;
     }

}

以及“时刻-持续时间-格式”的设置:“^2.3.2”

interface DurationSettings {
                trim: boolean | 'left' | 'right';
                useGrouping: boolean;
                usePlural: boolean;
                useLeftUnits: boolean;
                precision: number;
                useSignificantDigits: boolean;
                trunc: boolean;
                forceLength: boolean;
                minValue: number;
                maxValue: number;
                largest: number;
        }

相关问题