How to import external type into global .d.ts file

Viewed 17286

I'm using Moment.js to handle datetime objects in my TypeScript project. I would like to define an object type that has a key with a value of a type Moment.

However, when I add the following to a global definition file (test.d.ts), none of the interfaces in that file are found anywhere in the project.

import { Moment } from 'moment';

interface Test {
  date: Moment;
}

When I try to use the interface in a .ts or .tsx file I get this TypeScript error:

[at-loader] ./src/<examplefilename>.tsx:91:26 
    TS2304: Cannot find name 'Test'. 

Neither VSCode's TypeScript error checking nor TSLint show any problems with the code.

How can I import a type from an external module for use in a global definition file?

3 Answers

With TypeScript 3.3+ (and maybe since the 2.4 because it's the version that added support for dynamic imports), you have better ways to solve this isssue, using either:

interface Test {
  date: import('moment').Moment;
}

or

type Moment = import('moment').Moment;
interface Test {
  date: Moment;
}

with no need to export any interfaces ;)

Here's an example of a global.d.ts file in a Create React App project:

declare type RouteProps = import("react-router-dom").RouteProps;

declare interface Xyz extends RouteProps {
  yada: string;
}
Related