在TypeScript中使用MomentJS - moment()有什么类型?

Mr.*_*guy 24 momentjs typescript

我目前正在将我的项目从ES5转换为ES6,但我遇到了MomentJS(version 2.18.1)的问题.问题是我有一些变量是Moment对象,但是我不能在它们上面调用moment().

一个例子:

import * as moment from "moment";

export class DateThingy {

  constructor(private moment) { //What type does this have??
  }

  public getDate(): moment.Moment { 
    return this.moment();
  }
}
Run Code Online (Sandbox Code Playgroud)

1)如果我设置的类型private momentprivate moment: momentWebStorm抱怨:" 找不到名称'时刻’ "

2)如果我将类型设置private moment: moment.Moment为对象已更改,我不能再调用this.moment()(它现在是一个对象,并且没有函数调用).Webstorm告诉我:" 不能调用一个类型没有呼叫签名的表达式.类型'Moment'没有可以召集的呼叫签名. "

3)我不能再使用MomentStatic,因为它不会被导出.如果我输入private moment: moment.MomentStaticWebStorm给我:" 命名空间'时刻'没有导出的成员'MomentStatic' "

那么我应该为这个例子使用什么打字?

Mr.*_*guy 52

正如Mike McCaughan所说,当前对象无法在构造函数中注入.不知何故,这可能是旧版本的MomentJS.这可以通过删除构造函数属性并访问通过包含的全局矩对象来解决import * as moment from "moment".

该函数moment()返回一个Moment对象.这可以通过输入moment.Moment.

所以代码可以重写如下:

import * as moment from "moment";

export class DateThingy{

     constructor() {
     }

     public getDate(): moment.Moment { 
        return moment();
     }
}
Run Code Online (Sandbox Code Playgroud)


OHM*_*OHM 15

您是否尝试了不带别名的时刻导入?

import moment from 'moment';

这对我有用。而且打字稿编译器不会对此抱怨。

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

请注意,这需要tsconfig更新!

在TSConfig中,您需要添加选项allowSyntheticDefaultImports以允许默认导入没有默认导出的库。

示例(tsconfig.json):

{
  "compileOnSave": false,
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
  }
}
Run Code Online (Sandbox Code Playgroud)

  • @Kunok,您需要在tsconfig.json中添加`“ allowSyntheticDefaultImports”:true`(https://www.typescriptlang.org/docs/handbook/compiler-options.html),以便能够使用无默认以这种方式在打字稿中导出。 (2认同)

fre*_*ett 5

您可以像这样导入和使用时刻输入:

import moment, { Moment } from "moment";

const timeNow: Moment = moment();
Run Code Online (Sandbox Code Playgroud)

  • 这应该是公认的答案。为什么这个答案的票数这么少? (3认同)