1

我已经实现了一个模块,它采用两个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);
});

我收到以下 linting 错误:

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

寻找可以消除此错误的特定类型定义,例如moment.Moment.durationor moment.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'.

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

4

1 回答 1

2

根据您的导入情况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{ ... }
于 2018-10-30T11:40:41.447 回答