[英]How to import external type into global .d.ts file
I'm using Moment.js to handle datetime objects in my TypeScript project.我正在使用 Moment.js 来处理我的 TypeScript 项目中的日期时间对象。 I would like to define an object type that has a key with a value of a type Moment
.我想定义一个对象类型,它的键值为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.但是,当我将以下内容添加到全局定义文件 ( test.d.ts
) 时,在项目中的任何位置都找不到该文件中的任何接口。
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:当我尝试在.ts
或.tsx
文件中使用接口时,我收到此 TypeScript 错误:
[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. VSCode 的 TypeScript 错误检查和 TSLint 都没有显示代码有任何问题。
How can I import a type from an external module for use in a global definition file?如何从外部模块导入类型以在全局定义文件中使用?
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:使用 TypeScript 3.3+(也许从 2.4 开始,因为它是添加了对动态导入的支持的版本),您有更好的方法来解决这个问题,使用以下任一方法:
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.当文件具有顶级import
或export
语句时,它被视为一个模块。 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:以下是 Create React App 项目中global.d.ts
文件的示例:
declare type RouteProps = import("react-router-dom").RouteProps;
declare interface Xyz extends RouteProps {
yada: string;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.