简体   繁体   中英

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

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?

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';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM