Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use moment-duration-format in TypeScript?

I am using moment.js in my TypeScript (Ionic2/Angular2) project. Following on from this post, I now want to try out a plugin moment-duration-format

I have the npm package and the type definition and am able to use by import as..

import moment from 'moment';
...
let duration = moment.duration(decimalHours, 'hours');

I now want to use moment-duration-format

I have installed via npm install moment-duration-format --save and then the type definition via npm i @types/moment-duration-format --save.

I can see both npm modules.

As always, there is always some mystery on how to use such type definitions (the useage including import never seems to be in any doco).

I have tried adding import 'moment-duration-format';, import duration from 'moment-duration-format'; (moment-duration-format/index.d.ts' is not a module.)

I get an error when trying to use as follows..

let dd = moment.duration.format(400.99, 'hours').format('D:HH:mm');

// (TS error [ts] Property 'format' does not exist on type '(inp?: DurationInputArg1, unit?: DurationConstructor) => Duration'.

Does anyone have any idea on how to use this in TypeScript.

Thanks in advance

like image 430
peterc Avatar asked Mar 28 '17 00:03

peterc


People also ask

How do you use moment duration?

var duration = moment. duration("09:30"); var str = moment(duration. _data). format("HH:mm");

What is the use of moment in JavaScript?

Moment JS allows displaying of date as per localization and in human readable format. You can use MomentJS inside a browser using the script method. It is also available with Node. js and can be installed using npm.


2 Answers

I was using the workaround here, but it now looks like the ype def has been fixed. Getting an update of the type def So I can do the following...

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

let duration = moment.duration(decimalHours, 'hours') ;   
let options : moment.DurationFormatSettings   = {
  forceLength : false,
  precision : 0,
  template : formatString,
  trim : false
};
let result  = duration.format(formatString, 0, options);
like image 111
peterc Avatar answered Oct 05 '22 14:10

peterc


You are using duration as a property instead of invoking it. Try:

let dd = moment.duration(400.99, 'hours').format('D:HH:mm');

This is actually not a TypeScript problem. It wouldn't work with JavaScript either. In JavaSctript you would get a runtime error while TypeScript doesn't let you do it at compile time (proving its worth).

like image 27
Sefe Avatar answered Oct 05 '22 14:10

Sefe