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

标签 typescript import module elision typescript3.8

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

export interface MyInterface {
   // ...
}

export const enum MyEnum {
   // ...
}

export type MyType = {
  // ...
}

我已阅读有关新功能的信息 import type获取最新的 typescript here .据我所知,它旨在解决从 .js 文件导入时似乎主要发生的特定问题。

我可以同时使用 import 导入我的类型和 import type声明。两者似乎工作得同样好。问题是我应该更喜欢 import type更明确并帮助我避免一些理论上的边缘问题,或者我可以使用 import为简单起见并依赖 import elision从已编译的代码中删除这些?

换句话说:使用 import type 有什么好处吗?这里或者它应该用于特定情况来解决 import elision缺点?

最佳答案

简短回答:使用 import type 更加明确和 export type声明似乎通过 产生了可解释的好处防范边缘情况问题 ,以及 通过类型定义分析为当前和即将推出的工具提供更好的基础,以提高处理性能和可靠性 .
长答案:
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.


以下是两个实际示例,这些剩余导入如何在构建或运行时导致错误:
  • import type 修复的与类型相关的奇怪 Webpack 错误声明,博文:Leveraging Type-Only imports and exports with TypeScript 3.8
  • 关于 remnant imports causing circular dependency reference errors 的 SO 问题

  • 另一个好处与分析类型定义的工具有关。目前有关于使用 Babel 设置打包器的好处的详细信息,但目前或以后可能也会使其他工具受益(例如 IDE 性能)。
    对于 Babel 用户手动配置他们的设置:如果您在捆绑器设置中使用 Babel 7.9=> 和 TS 3.8=>,那么您可以删除以前需要的 @babel/plugin-transform-typescript插入。
    对于那些使用预先构建的 Babel 预设的设置:Babel 的团队建议配置 Babel 预设,以便使用显式的仅类型导入。
    在博客文章中阅读更多内容:Babel 7.9 Reduces Bundle Sizes, Adds TypeScript 3.8 Support .
    更多关于Using Babel with TypeScript的相关信息在 TS 文档中。
    详细了解使用的好处以及如何使用 isolatedModules TS 编译器选项有效 type-only imports — A new TypeScript feature that benefits Babel users

    关于typescript - 如果我的所有导入都来 self 自己的文件,我是否需要使用 TypeScript 3.8 的 "import type"功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61412000/

    相关文章:

    javascript - 通用组件中对象的类型为 'unknown' .ts(2571)

    java - 如何在不同的包中导入两个同名的类?

    python - Python 的 "import"内部是如何工作的?

    c - 如何在内核源文件中包含 math.h #include <math.h>?

    javascript - 对列表元素进行排序node.js

    json - typescript/angularJs 2 中的类型 'name' 不存在属性 'JSON'

    javascript - Angular:如何将时间从 00:00:01 转换为 8 分 49 秒格式?

    创建泛型方法的 Angular 最佳实践

    grails - 如何将包中的服务导入Grails中的gsp文件中

    Python - 理解 CSV 模块和 line_num 对象