javascript - 如何在 TypeScript 中以嵌套方式导出多个接口(interface)?

标签 javascript typescript npm es6-modules

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

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

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

这在 TypeScript 中是否可行,如果可以,如何实现?无效的是根目录中的此代码 index.ts文件:
export {
  Foo,
  { Bar }
};

请注意 .ts文件不在模块的根目录下,所以 .js.d.ts文件也不是。

我该如何解决这个问题?

PS:这里不是关于默认导出与命名导出,因为我想有一个解决方案来导出多个嵌套级别的接口(interface)。

最佳答案

在最简单的情况下,您只需要单独的 index.d.ts my-module 中的文件和 my-module/sub-part发布的npm包的文件夹,所以我们可以导入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解决my-modulemy-module/sub-part导入(假设不存在像 @types 这样的全局类型声明)。例如,my-moduleimport { Foo } from 'my-module'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)

希望能帮助到你。

关于javascript - 如何在 TypeScript 中以嵌套方式导出多个接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58587899/

相关文章:

javascript - console.log 是原子的吗?

javascript - Angular [ngClass] 条件和函数组合

css - 如何覆盖样式组件中的 css 类

javascript - Node Js 错误 Module.js 549

node.js - 由于可能与 Node 冲突,node-pre-gyp 安装错误

node.js - npm 安装 zmq 失败

javascript - React hooks - setState 不更新状态属性

javascript - 多次滑动函数调用

javascript - 在 AJAX 中获取 http ://url/route? id=clinic_id 404(未找到)

javascript - 类的静态端和实例端之间的区别