如何在 TypeScript 中以嵌套方式导出多个接口?

How do I export multiple interfaces in a nested way in TypeScript?

我有一个用 TypeScript 编写的相当大的 npm 模块,它公开了许多类型,包括几个接口。现在这些接口在根级别并不都有意义,这就是为什么我想以一种可以以某种嵌套方式导入的方式公开它们。

基本上,我正在寻找一种公开接口的方法,以便模块的用户可以执行以下操作:

import { Foo } from 'my-module';
import { Bar } from 'my-module/sub-part';

这在 TypeScript 中可行吗?如果可行,如何实现? 的作用是根index.ts文件中的这段代码:

export {
  Foo,
  { Bar }
};

请注意 .ts 文件不在模块的根目录中,因此 .js.d.ts 文件也不在。

我该如何解决这个问题?

PS:这与这里的默认导出与命名导出无关,因为我想要一个在 多个 嵌套级别中导出接口的解决方案。

在最简单的情况下,您只需在已发布的 npm 包的 my-modulemy-module/sub-part 文件夹中有单独的 index.d.ts 文件,因此我们可以导入 my-modulemy-module/sub-part分别。示例项目目录:

my-module
|   dist
│   index.ts
│   package.json // types prop e.g. could point to dist/index.d.ts
│
└───sub-part
        index.ts // compiled to dist/sub-part/index.d.ts

TS 利用其 module resolution process to resolve my-module or my-module/sub-part imports (given no global type declaration like @types exists). For example, my-module in import { Foo } from 'my-module' is resolved like this:

// first, try to find file directly
node_modules/my-module.ts
node_modules/my-module.tsx
node_modules/my-module.d.ts

// look in package.json for types property pointing to a file
node_modules/my-module/package.json // <-- lands here, if "types" prop exists

// look in @types
node_modules/@types/my-module.d.ts

// treat my-module as folder and look for an index file
node_modules/my-module/index.ts
node_modules/my-module/index.tsx
node_modules/my-module/index.d.ts // <-- lands here otherwise

为了这里的完整性,my-modulemy-module/sub-part 也可以在一个包含文件中定义为单独的 global module declarations,例如:

declare module "my-module" {
  const Foo: string
}

declare module "my-module/sub-part" {
  const Bar: number
}

最后,客户端代码看起来就像您想象的那样:

import { Foo } from "my-module";
import { Bar } from "my-module/sub-part";

console.log(Foo)

希望对您有帮助。