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

前端 未结 3 405
野性不改
野性不改 2021-02-05 00:16

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

相关标签:
3条回答
  • 2021-02-05 00:47

    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,
      }
    }
    
    0 讨论(0)
  • 2021-02-05 00:52

    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();
         }
    }
    
    0 讨论(0)
  • 2021-02-05 00:59

    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)

    0 讨论(0)
提交回复
热议问题