Typescript type definition for moment.js durations

I have implemented a module that takes two moment.js timestamps and a rounding rule and returns the rounded moment.js duration between those timestamps.

My first instinct was to use moment.Moment to specify the expected type of the output, as below.

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

But durations are different than moments.

On my spec file,

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

I get the following linting error:

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

Looking for or a specific types definition that would silence this error, like moment.Moment.duration or moment.duration:

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

yields

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

or

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

Which implementation would correct both errors?

Upvotes: 1

Views: 2194

Answers (1)

Stephen Wigginton
Stephen Wigginton

Reputation: 372

based on your import being import * as moment from 'moment', the type for Duration is moment.Duration, not moment.duration. Change this

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

to

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

Upvotes: 2

Related Questions