仅类型导入(Type-Only Import)
一句话解释
'import type' 仅导入类型——运行时擦除,防止意外将仅类型模块包含在包中。
用大白话说
import type 语法仅导入类型——不生成运行时代码。这帮助打包器摇树优化未使用的模块,并防止意外仅为类型导入模块。语法:import type { Foo } from "./foo" 或 import { type Foo, bar } from "./foo"(内联仅类型)。使用场景:1. 你只需要模块的类型(无运行时值)
- 想避免循环依赖问题
- 想确保模块不包含在运行时包中
verbatimModuleSyntax 编译器选项(TS 5.0+)强制对仅类型导入使用 import type。
示例
typescript
// Type-only import — erased at runtime
import type { Config, Options } from "./config";
// Mixed import — value + type
import { render, type Component } from "./ui";
// Usage
function setup(config: Config, comp: Component) {
render(comp); // render is a value, Component is a type
}
// After compilation, only `render` import remains
// import { render } from "./ui";import type 确保 Config、Options 和 Component 在编译时擦除。只有运行时值(render)保留在输出中。
常见混淆
容易混淆的对象: 常规导入
关键区别: 常规导入同时包含类型和运行时值——模块在运行时加载。import type 仅包含类型——导入被擦除,不生成运行时代码。只需要类型不需要值时用 import type。
相关术语
相关资源
相关课程
- TypeScript 模块
仅类型导入。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。