将 --isolatedModules 与 TS 3.2.2 一起使用时无法重新导出类型 [英] Cannot re-export a type when using the --isolatedModules with TS 3.2.2
问题描述
我可能需要重新思考我们构建 React 组件的方式.我们正在使用允许使用 Typescript 的最新 react-scripts,并且默认情况下,正在启用 isolatedModules
,这让我有点不舒服.
I probably need to rethink the way we structure our React components. We are using the latest react-scripts that allow Typescript to be used and by default, the isolatedModules
is being enabled which currently bugs me a bit.
我们过去常常像这样构建一个组件:
We used to structure a component like this:
Component
|_ Component.tsx
|_ index.ts
|_ types.ts
Component.tsx
保存没有声明的实际组件index.ts
只是重新导出所有内容,因此我们可以有一个单一的入口点,并且可以执行诸如import Component, { ComponentType } from '@/Component' 之类的操作;
Component.tsx
holds the actual component without declarationsindex.ts
is just re-exporting everything so we can have a singular entry point and can do something likeimport Component, { ComponentType } from '@/Component';
types.ts
保存实际的类型定义并导出大部分或全部.types.ts
holds the actual type definitions and exports most or all of them.到目前为止一切顺利,无需
isolatedModules
即可工作.然而,我们也导出了一些类型定义,有效地重新导出了在Component/types.ts
中指定的接口.这将不起作用,因为 TypeScript 本身不会再转译代码.So far so good and that works without the
isolatedModules
. However, we also export some of the type definitions, effectively re-exporting the interfaces that were specified withinComponent/types.ts
. This won't work as TypeScript itself would not transpile the code any longer.如何在没有单独导入语句的情况下将其重新导出到
@/Component/types
(这可能是实际更简单的方法)?How can I re-export this without having a separate import statement going to
@/Component/types
(which might be actual the simpler way anyway)?推荐答案
TS 3.8+
您可以使用 --isolatedModules 的noreferrer">仅类型导入和导出:
TS 3.8+
You can use type-only imports and exports with
--isolatedModules
:// types.ts export type MyType = { a: string; b: number; };
// main.ts // named import/export import type { MyType } from './types' export type { MyType } // re-export export type { MyType } from './types' // namespace import import type * as MyTypes from "./types"; export type RenamedType = MyTypes.MyType; export { MyTypes }; // ^ Note the "type" keyword in statements above
Example Playground; Take a look at the PR for possible extension forms and proposals.
在以前的版本中,以下是不可能的:
In previous versions, the following is not possible:
import { MyType } from './types'; export { MyType }; // error: Cannot re-export a type with --isolatedModules export { MyType } from "./types"; // error, like above
类型重新导出必须使用解决方法:
Type re-exports have to use a workaround:
import { MyType as MyType_ } from "./types"; export type MyType = MyType_; // or export * from "./types"
这篇关于将 --isolatedModules 与 TS 3.2.2 一起使用时无法重新导出类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!