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

Solution 1:

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

Solution 2:

Did you tried importing moment without alias?

import moment from 'moment';

This worked for me. And typescript compiler won't complain about it.

const date = moment().format('YYYYMMDD');

Note that this requires a tsconfig update!

In the TSConfig you need to add the option allowSyntheticDefaultImports to allow default imports of libraries that have no default exports.

Example (tsconfig.json):

{
  "compileOnSave": false,
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
  }
}

Solution 3:

You can import and use moment typing like so:

import moment, { Moment } from "moment";

const timeNow: Moment = moment();