【发布时间】:2020-08-27 20:43:16
【问题描述】:
我不明白到底发生了什么,也不明白为什么要这么做:
-
如果
Something是一个类型,为什么export { SomeThing } from "elsewhere"在启用--isolatedModules时会产生错误?相反,如果
Something是一个值,或者如果--isolatedModules未启用,为什么export { SomeThing } from "elsewhere"不是错误? 为什么指定
export type { SomeThing } from "elsewhere"会修复该错误?
(背景信息)
仅类型导入和导出
这个功能是大多数用户可能永远不需要考虑的; 但是,如果你在
--isolatedModules下遇到问题,TypeScript 的transpileModuleAPI,或者 Babel,这个特性可能是相关的。TypeScript 3.8 为纯类型导入和导出添加了新语法。
import type { SomeThing } from "./some-module.js"; export type { SomeThing };
import type仅导入用于类型的声明 注释和声明。它总是被完全擦除,所以 在运行时没有它的残余。同样,仅export type提供可用于类型上下文的导出,并且也是 从 TypeScript 的输出中删除。
我知道如何使用它以及何时使用它,但我不知道为什么,即显然当--isolatedModules 启用时,代码如下...
import type { SomeThing } from "./some-module.js";
export { SomeThing };
... 产生编译器错误,即 ...
Re-exporting a type when the '--isolatedModules' flag is provided requires using 'export type'.ts(1205)
...解决方法是使用export type { SomeThing } 而不是export { SomeThing }。
顺便说一句,import { SomeThing } from "./some-module.js" 显然是可以的,不会产生错误消息,import type { SomeThing } from "./some-module.js" 不是必需的。
顺便说一句,这与 What is `export type` in Typescript? 的主题不同,后者是关于在 2017 年实施此新功能之前定义一个 type 并为其添加前缀 export。
【问题讨论】:
标签: typescript