【问题标题】:Export a type after its declaration on Typescript 3.8+在 Typescript 3.8+ 上声明后导出类型
【发布时间】:2020-11-29 12:57:35
【问题描述】:

在使用 Typescript 3.8+ 声明类型后尝试导出类型时:

type Type = { Prop: string };
export { Type }

... VS Code 给出以下错误:

在提供--isolatedModuls 标志时重新导出类型需要使用export type

所以我按照错误提示做了:

type Type = { Prop: string };
export type { Type }

但是,这导致了另一个错误,由 eslint 发出:

解析错误:需要声明或声明。

2 个问题:

  1. 为什么会被视为“再出口”?
  2. Typescript 3.8+ 上是否允许这种导出,--isolatedModuls 标志打开,as explained here

【问题讨论】:

    标签: typescript export


    【解决方案1】:

    我设法解决了我的问题:

    1. --isolatedModuls 标志打开时,VS Code's TypeScript language service 无法判断我们尝试导出的类型是否源自当前模块。

      还有一个类似的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,所以它需要包含在结果输出中)。

    2. 正如错误提示的那样,这样做的方法确实是:

      type Type = { Prop: string };
      export type { Type }
      

      正如我的问题中所述,这导致 eslint 发出错误,但该错误实际上是错误的。我无法消除该错误,并最终重新创建了我的 Typescript 应用程序,该应用程序成功了。
      因此,对于未来的读者,请确保您遵循正确的安装:

      // the following creates a typescript app, and installs required type declarations, 
      // which are: @types/node @types/react @types/react-dom @types/jest
      npx create-react-app hello-world --template typescript
      
      // you'd probably work with react-redux, so install it as follows:
      cd hello-world
      npm install --save redux @types/redux
      npm install --save react-redux @types/react-redux 
      

      对于 eslint,Typescript 的 eslint 模块,名为@typescript-eslint,按照以上步骤安装在 node_modules 下即可。您可以通过标记一个未使用的变量来验证这一点:

      const a = 1;
      

      这会导致@typescript-eslint 发出警告:

      'a' 被赋值但从未使用过

      附言

      请注意,eslint 本身仍然会发出一些错误,而不是 @typescript-eslint。例如,尝试错误地导出我们在上面声明的变量a,如下所示:

      const a = 1;
      export a; // gives an error
      

      ...你会得到前面提到的 eslint 发出的解析错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-12
      • 1970-01-01
      • 2016-12-06
      • 2019-06-29
      • 1970-01-01
      • 2018-09-23
      • 2017-12-31
      • 2021-01-03
      相关资源
      最近更新 更多