How do I import third-party module in declaration file(*.d.ts)?

1.1k Views Asked by At

I created the type declaration file(index.d.ts), and I need to use an object of the third-party package('moment.js' in node_modules) as type.


  // index.d.ts

  import * as Moment from 'moment';

  declare var $: any;
  declare var google: any;

  interface foo {
    a: Moment;
    b: string;
    ...
  } 

I made a code like above, but it doesn't work. How do I import a third-party module in *.d.ts file?

1

There are 1 best solutions below

0
On BEST ANSWER

The .d.ts file that ships with Moment wraps wraps everything it exports into a namespace. So for this lib, importing like import * as Moment from 'moment'; means the Moment variable is a namespace not the interface for a Moment instance itself. What you want is the interface that lives inside the namespace.

You have two options to handle this:

  import * as moment from 'moment';

  interface foo {
    a: moment.Moment;
    b: string;
  } 

Or deconstruct the interface during the import:

  import { Moment } from 'moment';

  interface foo {
    a: Moment;
    b: string;
  } 

Personally, I use the first style for files of mine that use lots exported members from the namespace, but if I only need a few I use the second style.

edit...

If your tsconfig has esModuleInterop enabled (which is the newish preferred setting), the import from first example can/should remove the * as bit.

import moment from 'moment';