Moment.js持续时间的Typescript类型定义

时间:2018-10-30 06:38:26

标签: typescript types momentjs

我已经实现了一个模块,该模块采用两个moment.js时间戳和一个舍入规则,并返回这些时间戳之间的舍入moment.js持续时间。

我的第一个直觉是使用moment.Moment指定预期的输出类型,如下所示。

export default function roundDuration(
  startTime: moment.Moment,
  endTime: moment.Moment,
  timeRoundingRule: number
): moment.Moment {
  const duration = moment.duration(endTime.diff(startTime));
  // calculate rounded duration based on rounding rule
  return roundedDuration;
}

但是持续时间不同于瞬间。

在我的规格文件中,

import * as moment from 'moment';
import roundDuration from './rounding';

test('roundDuration rounds zero seconds to zero minutes duration using rule UpToNearestMinute', () => {
  const startTime = moment('05-17-2018 23:40:00', 'MM-DD-YYYY hh:mm:ss');
  const endTime = moment('05-17-2018 23:40:00', 'MM-DD-YYYY hh:mm:ss');
  const timeRoundingRule = 0;
  const roundedTime = roundDuration(startTime, endTime, timeRoundingRule);
  expect(roundedTime.asMinutes()).toBe(0);
});

我收到以下棉绒错误:

[ts] Property 'asHours' does not exist on type 'Moment'. Did you mean 'hours'?

寻找或可以使该错误消失的特定类型定义,例如moment.Moment.durationmoment.duration

export default function roundDuration(
    startTime: moment.Moment,
    endTime: moment.Moment,
    timeRoundingRule: number
): moment.Moment.duration { ... }

收益

[ts] Namespace 'moment' has no exported member 'Moment'.

[ts] Namespace 'moment' has no exported member 'duration'.

哪种实现可以纠正这两个错误?

1 个答案:

答案 0 :(得分:1)

根据您的导入为import * as moment from 'moment',Duration的类型为moment.Duration,而不是moment.duration。改变这个 export default function roundDuration( startTime: moment.Moment, endTime: moment.Moment, timeRoundingRule: number ): moment.Moment.duration { ... }

export default function roundDuration( startTime: moment.Moment, endTime: moment.Moment, timeRoundingRule: number ): moment.Duration{ ... }