如果我的所有导入都来自我自己的文件,我是否需要使用 TypeScript 3.8 的 "import type" 功能?

Do I need to use the "import type" feature of TypeScript 3.8 if all of my imports are from my own file?

我有一个简单的文件 types.ts 定义了一些类型:

export interface MyInterface {
   // ...
}

export const enum MyEnum {
   // ...
}

export type MyType = {
  // ...
}

我已阅读有关最新打字稿 here 的新功能 import type。据我了解,它旨在解决从 .js 文件导入时似乎主要发生的特定问题。

我可以使用 importimport type 语句导入我的类型。两者似乎都一样好用。问题是我应该更喜欢 import type 来更明确并帮助我避免一些理论上的边缘情况问题,还是我可以只使用 import 来简化并依靠 import elision 从中删除这些问题编译代码?

换句话说:在这里使用 import type 是否有任何好处,或者它应该用于特定情况以解决 import elision 缺点?

简短回答: 通过使用 import typeexport type 语句更明确似乎可以通过 防止 edge-case 问题,以及 通过类型定义分析为当前和即将推出的工具提供更好的基础,以提高处理性能和可靠性

长答案:

正如TypeScript 3.8 release notes所说:

import type only imports declarations to be used for type annotations and declarations. It always gets fully erased, so there’s no remnant of it at runtime. Similarly, export type only provides an export that can be used for type contexts, and is also erased from TypeScript’s output.

下面是两个实际示例,这些剩余导入如何导致构建或运行时出错:

另一个好处与分析类型定义的工具有关。目前有关于使用 Babel 的捆绑器设置的好处的详细信息,但目前或以后可能也会使其他工具受益(例如 IDE 性能)。

对于手动配置其设置的 Babel 用户:如果您在使用 TS 3.8=> 的捆绑器设置中使用 Babel 7.9=>,那么您可以删除之前需要的 @babel/plugin-transform-typescript 插件。

对于那些使用 pre-built Babel 预设的设置:Babel 的团队建议配置 Babel 预设,以便使用显式 type-only 导入。

在博客中阅读更多内容 post:Babel 7.9 Reduces Bundle Sizes, Adds TypeScript 3.8 Support

TS 文档中有关 Using Babel with TypeScript 的更多相关信息。

详细了解使用 isolatedModules TS 编译器选项的好处以及如何工作 type-only imports — A new TypeScript feature that benefits Babel users