javascript - typescript:在 typescript 项目中使用声明文件来全局公开类型
问题描述
我最近开始使用打字稿。我有一个打字稿项目设置,其中有很多用打字稿编写的 React 组件。这些 typescript 组件通常会导出组件本身,为了方便开发,我已将这个 typescript 组件所需的所有类型提取到一个单独的文件中。现在通常你必须在你的组件中导入这些类型才能使用它,但由于它很麻烦,团队中的某个人想出了一个想法,将这些包含类型的单独文件命名为types.d.ts
(或任何.d.ts)。这使得类型在整个项目中全局可用,而无需在任何地方显式导入类型。
现在,我知道只有在我的 typescript 项目中使用 javascript 组件,并且如果我想对该 javascript 组件进行类型检查时才需要类型声明文件。在这种情况下,我可以从外部获取类型声明文件(例如,DefiniteTyped),或者我可以创建一个本地声明文件。这不是我在这里使用声明文件的目的。
但我想了解这种用法有什么问题?
- 全局公开所有类型是否错误(请注意,这些类型中的大多数仅在组件内部需要,其他使用该组件的组件仅需要一些类型)?
- 由于这个原因,编译器或打字稿设置会有什么问题吗?
- 我已经阅读了一个生成声明文件的编译器选项,这个设置会干扰吗?
注意:这个名为 d.ts 的单独文件并不真正遵循声明文件可能需要的任何特定准则。这只是有一些常规的接口声明
解决方案
Some observations:
in a
.ts
file (or ad.ts
file), if there is no top level export, it would be considered a global script (similar to how this works in javascript) and everything in the script would be available globally. This is how the types are exposed globally in my case (again, it does not have to be a.d.ts
file)if you a
ts
file and ad.ts
file with the same name, the compiler ignores thed.ts
file and that is why it is not possible to expose types forComponent.tsx
usingComponent.d.ts
(you would need to name thed.ts
file something else)when importing an external module without type information, typescript suggests to add a
d.ts
file withdeclare module moduleName
, instead of this you can also just add a regular .d.ts file with a top level export insidemoduleName/index.d.ts
So, to answer my questions:
it might not be wrong to expose all the types globally used within your application, but then you have to take care of any namespacing/naming conflicts. In this case, using
d.ts
file is not required, this setup would just work as well with a.ts
file exposing the types globally. Another way to achieve this would be to export types from respective files and import them wherever required.in this setup, the only problem with the compiler which may arise is when the
.d.ts
file is named same as the.ts
file, in which case the.ts
file would override and types from.d.ts
would not be available globally.the compiler generates the declaration files from
ts
files, and that is mostly required if you need to publish your types. In our case, the types are internal and we won't really need to generate the declarations. Our usage, as discussed, is not dependent on the file being a declaration file, it will work just as well in a.ts
file and we shouldn't be using.d.ts
file for this. So, no, there wouldn't be any impact.
推荐阅读
- java - Java - 地图
> 遍历列表并跳过前 N 个条目 - pos-tagger - POS/NER 能够区分在多个上下文中使用的同一个词吗?
- php - 如何反序列化,然后将生成的多维数组转换为纯文本,去掉代码?
- azure - 将 Azure Sql 数据库限制为只能从不同区域的某些 Azure 应用服务访问
- python - 如何在 Pandas 中更改 MultiIndex 数据框列中某些行的值
- python - 使用 PySimpleGUI 时如何启用并响应最大化按钮
- vue.js - Vuetify:尽管 v-model 变量设置为 false,但 v-dialog 不会关闭
- c++ - 错误 LNK2005 DllMain 已在 uafxcw.lib(dllmodul.obj) 中定义
- javascript - 如何在 javascript 中为 ("1:2,2.2,3:4,4.1,5") 制作正则表达式?
- asp.net - 如何在 ASP.NET Core 的不同位置使用视图组件的视图?