Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using MomentJS with TypeScript - What type does moment() have?

I am currently converting my project from ES5 to ES6, but I am running into an issue with MomentJS (version 2.18.1). The problem is that I have a few variables that are Moment objects, but I cannot call moment() on them.

An example:

import * as moment from "moment";  export class DateThingy {    constructor(private moment) { //What type does this have??   }    public getDate(): moment.Moment {      return this.moment();   } } 

1) If I set the type of private moment to private moment: moment WebStorm complains: "cannot find name 'moment'."

2) If I set the type to private moment: moment.Moment the object has changed and I cannot call this.moment() anymore (it is now an object and does not have a function call on it). Webstorm tells me: "cannot invoke an expression whose type lacks a call signiture. Type 'Moment' has no campatible call signatures."

3) I cannot use MomentStatic anymore, since it is not exported. If I type private moment: moment.MomentStatic WebStorm gives me: "namespace 'moment' does not have an exported member 'MomentStatic'"

So what typing should I use for this example?

like image 580
Mr.wiseguy Avatar asked Jul 18 '17 15:07

Mr.wiseguy


People also ask

What is moment type in TypeScript?

The function moment() returns a Moment object. This can be typed via moment. Moment . So the code can be rewritten as follows: import * as moment from "moment"; export class DateThingy{ constructor() { } public getDate(): moment. Moment { return moment(); } }

What is 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.

How do I use moment timezone in TypeScript?

Use Typescript @types packages and import it via import * as moment from 'moment-timezone'; You can use all moment methods and member vars as moment-timezone exports them. Show activity on this post. Show activity on this post.


1 Answers

As Mike McCaughan said, the moment object cannot be injected in the constructor. Somehow this was possible with an old version of MomentJS. this could be resolved by removing the constructor property and accessing the global moment object that is included via import * as moment from "moment".

The function moment() returns a Moment object. This can be typed via moment.Moment.

So the code can be rewritten as follows:

import * as moment from "moment";  export class DateThingy{       constructor() {      }       public getDate(): moment.Moment {          return moment();      } } 
like image 124
Mr.wiseguy Avatar answered Sep 24 '22 13:09

Mr.wiseguy