【问题标题】:Why is `export type` necessary with `--isolatedModules`?为什么 `--isolatedModules` 需要`export type`?
【发布时间】:2020-08-27 20:43:16
【问题描述】:

我不明白到底发生了什么,也不明白为什么要这么做:

  • 如果Something 是一个类型,为什么export { SomeThing } from "elsewhere" 在启用--isolatedModules 时会产生错误?

    相反,如果Something 是一个值,或者如果--isolatedModules 未启用,为什么export { SomeThing } from "elsewhere" 不是错误?

  • 为什么指定 export type { SomeThing } from "elsewhere" 会修复该错误?


(背景信息)

a new TypeScript feature

仅类型导入和导出

这个功能是大多数用户可能永远不需要考虑的; 但是,如果你在--isolatedModules 下遇到问题,TypeScript 的 transpileModule API,或者 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


    【解决方案1】:

    this Babel Github issue,这里有解释:

    为了判断某物是否是类型,我们需要信息 关于其他模块。

    import { T } from "./other-module";
    export { T }; // Is this a type export?
    

    this Reddit thread上也有详细解释:

    类型空间是 TypeScript 的领域:构成你的所有类型 应用程序。它们仅在编译时存在。编译完成后, 结果 JavaScript 中没有任何类型。价值空间基本上是 相反:它是那些留在周围并存活下来的东西 JS。

    type Foo = { bar: string };
    const a: Foo = { bar: 'hello' };
    

    这里,Foo 在类型空间中, 其他一切都在价值空间中。

    isolatedModules 的问题是他们不知道他们在哪个空间 正在使用,因为每个文件都是单独编译的。所以如果你 做:

    export { Foo } from './bar';
    

    在文件中,TypeScript 无法知道 Foo 在类型空间中(如果是,它只是被扔掉,因为它不会 在生成的 JavaScript 中),或者如果它在值空间中(即 它是 JS,所以它需要包含在结果输出中)。

    【讨论】:

      猜你喜欢
      • 2023-01-14
      • 2015-07-18
      • 2012-01-16
      • 2020-04-20
      • 2017-03-04
      • 2019-06-09
      • 1970-01-01
      相关资源
      最近更新 更多