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?
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.
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 ;)
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
};
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With