如何将外部类型导入全局 .d.ts 文件 [英] How to import external type into global .d.ts file
问题描述
我正在使用 Moment.js 来处理我的 TypeScript 项目中的日期时间对象.我想定义一个对象类型,它的键值为 Moment
类型.
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
.
但是,当我将以下内容添加到全局定义文件 (test.d.ts
) 时,在项目中的任何位置都找不到该文件中的任何接口.
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;
}
当我尝试在 .ts
或 .tsx
文件中使用接口时,我收到此 TypeScript 错误:
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'.
VSCode 的 TypeScript 错误检查和 TSLint 均未显示代码存在任何问题.
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?
推荐答案
当文件具有顶级 import
或 export
语句时,它被视为一个模块.您感兴趣的所有内容(类型、接口等)都需要在该文件中显式导出,然后导入到需要这些类型的文件中.
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
};
这篇关于如何将外部类型导入全局 .d.ts 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!