简体   繁体   English

如何在 TypeScript 中导入和导出命名空间、接口和类型? 从索引文件?

[英]How to import and export namespaces, interfaces and types in TypeScript? from index file?

I want to declare a module and define its Types and Interfaces without repeat my self - so I can define a type and if it is something that can be shared, to use it again from elsewhere.我想声明一个模块并定义它的类型和接口而不重复我自己 - 所以我可以定义一个类型,如果它是可以共享的东西,可以从其他地方再次使用它。

So if for example I have a module called: User, I want to define a namespace called User and under it to define an Interface called Address and under Address to define one or more Types.因此,例如,如果我有一个名为:User 的模块,我想定义一个名为 User 的命名空间,并在其下定义一个名为 Address 的接口,并在 Address 下定义一个或多个类型。

Now, Address Type is something that I probably going to use in other modules - not specific to User, but also to Order for example.现在,地址类型是我可能会在其他模块中使用的东西 - 不是特定于用户,也适用于订单。

So I thought about creating a Interface directory and in this directory to add some files, each file per Interface and import all of those Interfaces to an index.ts file so it can be imported from anywhere of the app - actually even from other packages and modules and services that are not from within the same app.所以我考虑创建一个接口目录并在这个目录中添加一些文件,每个接口的每个文件并将所有这些接口导入到 index.ts 文件中,以便可以从应用程序的任何位置导入它 - 实际上甚至从其他包和不在同一个应用程序中的模块和服务。

For example:例如:

Interfaces
  Address.ts
  Contact.ts
  Role.ts
  index.ts

// index.ts

import Address from './Address'
import Contact from './Contact'
...etc

export default { Address, Contact }

But this won't work.但这行不通。 Because TS only help to write code, it won't add actual modules to the code and export it the way I mentioned above is meant for actual modules, not just Types and Interfaces!因为 TS 只帮助编写代码,它不会将实际模块添加到代码中并将其导出,我上面提到的方式适用于实际模块,而不仅仅是类型和接口!

So how can I export and import TS objects (Types, Interfaces, Namespaces, etc)?那么如何导出和导入 TS 对象(类型、接口、命名空间等)?

What is the best practice?最佳做法是什么? can you please provide a demo structure of it?你能提供一个演示结构吗?

Something like this...像这样的东西... 来自代码沙箱的快照

I made aCode Sandbox here which just prints some data to the console to prove type imports are working.我在这里制作了一个代码沙箱,它只是将一些数据打印到控制台以证明类型导入正在工作。 This is based on having a types.ts file with types in, and importing them from there into an index.ts so you can indeed import types from another file in Typescript.这是基于拥有一个包含类型的 types.ts 文件,并将它们从那里导入到 index.ts 中,因此您确实可以从 Typescript 中的另一个文件导入类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM