我正在尝试组织我的 TS 项目,并且我已将大部分类和接口(interface)移至 /models
目录中。为了让我自己/ future 的开发人员更轻松,我认为制作一个顶级 models.ts
文件来导入所有模型,然后重新导出它们会让事情变得更容易。
为此,我想到创建一个名为 Models
的命名空间/模块,然后导出该命名空间/模块。但是,我在尝试将导入的内容链接到导出的模块时遇到了问题,如下所示:
import {Args} from "./models/args";
import {Response} from "./models/response";
import {Inventory} from "./models/inventory";
export module Models {
// Trying things like:
// this.Args = Args --- nope, not a class
// Args = Args -- nope
// export Args -- nope
// export class Args -- nope
// export class ArgsModel extends Args -- nope
//
// This works, but it's renaming, and it feels hackish.
export class ArgsModel extends Args {}
//
// import export Args from "./models/args" -- nope, cant import from within a module
}
搜索了一段时间,我发现了很多关于模块的信息,但没有什么特别解决这个问题,这让我意识到这可能不是 TS 使用的模式。为此,我发现这里提出了类似的问题How to export multiple imported classes as a module产生的答案建议做这样的事情:
export * from "./models/args"
export * from "./models/response"
export * from "./models/inventory"
但是,我也觉得我已经在这个兔子洞里走得太远了,我想弄清楚我将如何实现我的初衷,以便我可以更好地理解 typescript 。
如何导出包含已导入的类、接口(interface)和模块的单个命名空间?
最佳答案
I thought of making a namespace/module called Models and then exporting that namespace/module.
您的文件是一个模块
。您不需要使用命名空间
。更多:https://basarat.gitbooks.io/typescript/content/docs/project/namespaces.html与模块:https://basarat.gitbooks.io/typescript/content/docs/project/modules.html
I also feel I've gone so far down this rabbit hole that I want to figure out how I would go about my original intention simply so I can understand typescript a bit better.
模块导入/导出需要可静态分析,因此被限制在文件的根处。
但是,您可以从 namespace 重新导出它们(如果您真的非常想要的话)。请注意,您需要将 root 重命名为不同的名称,否则在模块内它将被隐藏。
import {Args as ArgsModel} from "./models/args";
export namespace Models {
export const Args = ArgsModel;
}
关于javascript - 导出由导入的类/接口(interface)组成的模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37197921/