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

Viewed 59026

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?

4 Answers

You can import and use moment typing like so:

import moment, { Moment } from "moment";

const timeNow: Moment = moment();

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

I got Error message like this

Cannot invoke an expression whose type lacks a call signature. Type 'typeof moment' has no compatible call signatures.

My issue was importing with alias

import * as momentns from 'moment';

I changed this to

import moment from 'moment';

solved for me in angular 8(TypeScript 2.4)

Related