我有一个同时使用 .ts
的 TypeScript 应用程序和 .d.ts
文件。使用三重斜杠表示法进行引用 /// <reference path=...>
.我的应用程序具有以下定义文件:
declare module APP {
class Bootstrap {
constructor();
}
}
然后我声明一个名为 "app"
的模块这样我就可以将它导入到其他文件中:
declare module "app" {
export = APP;
}
假设我的 Bootstrap
类存在,然后我导入 Bootstrap
类使用:
import { Bootstrap } from 'app';
这有效。
现在我在 APP
上创建了一个子模块,像这样:
declare module APP.Service {
class Async {
constructor();
}
}
我为子模块做了另一个声明:
declare module "app/service" {
export = APP.Service;
}
现在,当我导入类时 Async
像这样:
import { Async } from 'app/service';
我收到以下错误消息:
Module '"app/service"' resolves to a non-module entity and cannot be imported using this construct.``
如何从子模块导入类?
注意
我通过声明全局 var
找到了解决方法:
declare var APP_SERVICE: APP.Service.IService; // IService exists
并将其导出到我的模块中:
declare module "app/service" {
export = APP_SERVICE;
}
这样做的缺点是我的全局 namespace 被 var
污染了我不使用,因为我会使用 Service
通过App.Service
, 不是 APP_SERVICE
.
最佳答案
如果您关心为模块创建一个漂亮的、可重用的、可维护的声明文件,首选方法是使用 typings ,因为它可以很好地为您处理类型依赖管理和子模块等方面。
- 为您正在编写的类型创建一个单独的存储库。
添加
typings.json
文件,其中包含您的主要类型的名称和路径。例如:{ "name": "my-main-module", "main": "index.d.ts" }
将主模块的类型声明添加到
index.d.ts
,将子模块的类型声明添加到submodule-name.d.ts
。submodule.d.ts
export interface submoduleInterface { someProp: number }
index.d.ts
import * as submodule from './submodule' export interface mainInterface { someProp: number }
运行
typings bundle index.d.ts -o bundle.d.ts
。这会将您所有的类型绑定(bind)到一个类型声明文件中,声明正确的子模块并尊重模块、子模块甚至外部模块之间的所有必要依赖关系。将此文件复制到原始项目中的
custom-typings
目录,或将此 repo 提交到 typings registry所以其他人也可以从中获利 🙂,并使用正常的typings i my-module-name
将其引入。
这是 gist包含所有代码,以及生成的 bundle.d.ts
。这是一个 repo它使用两个子模块 (redux-persist/constants
) 作为外部依赖项 (redux
),并且最终提交给了 typings 注册表。
关于javascript - TypeScript:如何从子模块导入类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39154473/