将MomentJS与TypeScript一起使用-moment()有什么类型? [英] using MomentJS with TypeScript - What type does moment() have?

查看:2071
本文介绍了将MomentJS与TypeScript一起使用-moment()有什么类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

一个例子:

import * as moment from "moment";

export class DateThingy {

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

  public getDate(): moment.Moment { 
    return this.moment();
  }
}

1)如果我将private moment的类型设置为private moment: moment,WebStorm会抱怨:"找不到名称'moment'."

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

2)如果将类型设置为private moment: moment.Moment,则对象已更改,并且无法再调用this.moment()(它现在是对象,并且不能对其进行函数调用). Webstorm告诉我:"无法调用类型缺少呼叫签名的表达式.类型'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)我不能再使用MomentStatic,因为它没有被导出.如果我键入private moment: moment.MomentStatic,WebStorm会给我:"命名空间'moment'没有导出的成员'MomentStatic'"

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?

推荐答案

正如 Mike McCaughan 所说,无法将对象注入构造函数中.某种程度上,使用旧版本的MomentJS可以实现.这可以通过删除构造函数属性并访问通过import * as moment from "moment"包含的全局矩对象来解决.

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".

函数moment()返回Moment对象.可以通过moment.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();
     }
}

这篇关于将MomentJS与TypeScript一起使用-moment()有什么类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆