首页 > 解决方案 > typescript:在 typescript 项目中使用声明文件来全局公开类型

问题描述

我最近开始使用打字稿。我有一个打字稿项目设置,其中有很多用打字稿编写的 React 组件。这些 typescript 组件通常会导出组件本身,为了方便开发,我已将这个 typescript 组件所需的所有类型提取到一个单独的文件中。现在通常你必须在你的组件中导入这些类型才能使用它,但由于它很麻烦,团队中的某个人想出了一个想法,将这些包含类型的单独文件命名为types.d.ts(或任何.d.ts)。这使得类型在整个项目中全局可用,而无需在任何地方显式导入类型。

现在,我知道只有在我的 typescript 项目中使用 javascript 组件,并且如果我想对该 javascript 组件进行类型检查时才需要类型声明文件。在这种情况下,我可以从外部获取类型声明文件(例如,DefiniteTyped),或者我可以创建一个本地声明文件。这不是我在这里使用声明文件的目的。

但我想了解这种用法​​有什么问题?

注意:这个名为 d.ts 的单独文件并不真正遵循声明文件可能需要的任何特定准则。这只是有一些常规的接口声明

标签: javascriptreactjstypescript

解决方案


Some observations:

  • in a .ts file (or a d.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 a d.ts file with the same name, the compiler ignores the d.ts file and that is why it is not possible to expose types for Component.tsx using Component.d.ts (you would need to name the d.ts file something else)

  • when importing an external module without type information, typescript suggests to add a d.ts file with declare module moduleName, instead of this you can also just add a regular .d.ts file with a top level export inside moduleName/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.


推荐阅读