Categories
TypeScript Answers

How to use Moment.js with TypeScript?

Spread the love

Sometimes, we want to use Moment.js with TypeScript.

In this article, we’ll look at how to use Moment.js with TypeScript.

How to use Moment.js with TypeScript?

To use Moment.js with TypeScript, we can use the types provided by moment.

For instance, we write

import * as moment from "moment";

class DateClass {
  constructor() {}

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

to import the whole moment module with

import * as moment from "moment";

Then in the getDate method, we set the return type of it to moment.Moment, which is the type for objects returned by moment.

Therefore, returning moment() matches the moment.Moment and the TypeScript compiler will accept this code.

Conclusion

To use Moment.js with TypeScript, we can use the types provided by moment.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.