【问题标题】:How to import external type into global .d.ts file如何将外部类型导入全局 .d.ts 文件
【发布时间】:2018-01-07 07:04:53
【问题描述】:

我正在使用 Moment.js 来处理我的 TypeScript 项目中的日期时间对象。我想定义一个对象类型,其键的值类型为Moment

但是,当我将以下内容添加到全局定义文件 (test.d.ts) 时,在项目的任何地方都找不到该文件中的任何接口。

import { Moment } from 'moment';

interface Test {
  date: Moment;
}

当我尝试在 .ts.tsx 文件中使用该接口时,我收到以下 TypeScript 错误:

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

VSCode 的 TypeScript 错误检查和 TSLint 均未显示代码有任何问题。

如何从外部模块导入类型以在全局定义文件中使用?

【问题讨论】:

  • 我会检查 tsconfig 文件。在编译器选项 - typeroots 你应该有 @types 路径和你的打字路径
  • @kimy82,我认为问题不存在。我可以在整个项目中很好地导入时刻,但我无法在我的项目的 .d.ts 定义文件中导入它以在我的项目中定义使用 Moment 类型的全局类型。我的其余 .d.ts 文件无需配置即可找到,只要我不尝试导入外部类型即可工作。
  • 你的tsconfig.json项目中是否也包含了带有全局变量的d.ts文件?
  • @MattBierner:是的。在我添加导入语句之前,可以在整个项目中访问该文件及其接口。此时编译器不再找到接口,我收到上面发布的错误。

标签: typescript momentjs typescript2.0


【解决方案1】:

使用 TypeScript 3.3+(可能是从 2.4 开始,因为它是添加了对动态导入支持的版本),您有更好的方法来解决这个问题,使用以下任一方法:

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

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

无需导出任何接口;)

【讨论】:

  • 如果我要分离我的类型,你会如何使用自定义界面来做到这一点?这也适用于扩展吗?即interface IUser extends import ('mongoose').document {}?
  • @Borduhh 的问题在我的回答中得到了解决。
  • type Transaction = import("../../../generated/graphql-frontend").Transaction
【解决方案2】:

当文件有顶级importexport 语句时,它被视为一个模块。您感兴趣的所有内容(类型、接口等)都需要在该文件中显式导出,并在需要类型的文件中导入。

// 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
};

【讨论】:

  • 解决了问题,谢谢!现在仅仅因为我导入了一个东西就不得不手动导出我的所有接口,这有点令人沮丧。
  • 如果使用export可以去掉declare。 export interface IInterface ....
【解决方案3】:

以下是 Create React App 项目中 global.d.ts 文件的示例:

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

declare interface Xyz extends RouteProps {
  yada: string;
}

【讨论】:

  • 非常感谢。谢谢
  • 正是我想要的!在 ts 4.4 中完美运行
猜你喜欢
  • 2018-03-12
  • 2017-01-14
  • 2017-08-06
  • 1970-01-01
  • 1970-01-01
  • 2017-02-09
  • 1970-01-01
  • 2021-02-03
  • 2016-12-26
相关资源
最近更新 更多