Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 538
keawade Avatar asked Jul 31 '17 15:07

keawade


People also ask

What is file type D ts?

The "d. ts" file is used to provide typescript type information about an API that's written in JavaScript. The idea is that you're using something like jQuery or underscore, an existing javascript library. You want to consume those from your typescript code.


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

like image 85
Hugo Capocci Avatar answered Oct 20 '22 05:10

Hugo Capocci


When file has top-level import or export statement it is considered as a module. All its' content (types, interfaces, etc.) you are interested in needs to be exported explicitly in that file and imported in those files that need the types.

// types.d.ts
import { Thingy } from 'sick-lib';

export declare interface IInterface {
  foo: any;
  bar: any;
  baz: Thingy;
}

// main.ts
import { IInterface } from 'types';

const xyz: IInterface = {
  foo: true,
  bar: false
};
like image 38
Konstantin Vitkovsky Avatar answered Oct 20 '22 03:10

Konstantin Vitkovsky


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;
}
like image 16
Wayne Bloss Avatar answered Oct 20 '22 05:10

Wayne Bloss