Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

moment-duration-format.d.ts Definition Not Extending Moment Module

Any idea why this doesn’t work or how I can extend the duration interface to support the format function?

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

}

when used as:

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

I’m getting the error that ‘format' does not exist on type ‘Duration'

like image 252
Jason Biondo Avatar asked Dec 29 '16 16:12

Jason Biondo


3 Answers

First, install types:

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

Second, import them in your file:

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

Then you can use

moment.duration(minutes, 'minutes').format('mm');
like image 102
Oleksiy Kachynskyy Avatar answered Sep 22 '22 04:09

Oleksiy Kachynskyy


Imports:

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

Outside of your class, define the interfaces:

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

Then in your code:

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

If you defined your Duration interface in another file, you will need to export and import it as well.

like image 24
fxlemire Avatar answered Sep 22 '22 04:09

fxlemire


You need to have the following dependencies installed:

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

If that's the case then you need these imports in the exact same order:

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

Afterwards you should be able to do this:

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]',
});
like image 38
Benny Neugebauer Avatar answered Sep 20 '22 04:09

Benny Neugebauer