如何为第三方 javascript 项目重新导出 global.d.ts 类型?

How to re-export global.d.ts typings for a third-party javascript project?

尽管我可以创建允许我的打字稿模块使用来自第三方javascript模块的函数定义的类型,这似乎又会为导入我的模块的包带来问题。

我填充了一个 global.d.ts 文件来为我的打字稿项目添加以下类型,因为 pouchdb-collate 是一个没有 @types 包的纯 javascript 项目...

// global.d.ts
declare module "pouchdb-collate" {
  export function toIndexableString(item: any): string;
  export function parseIndexableString(indexableString: string): any;
}

这在我的项目 A 中的 monorepo 中运行良好,该项目使用 pouchdb-collat​​e 并在其 src/ 中包含 global.d.ts。但是,每当我在 monorepo 中将项目 A 导入项目 B 时,项目 B 将无法使用 pouchdb-collat​​e 的类型,这会导致类似...

的错误
    ../collate/src/index.ts:4:8 - error TS7016: Could not find a declaration file for module 'pouchdb-collate'. '/project/blabla/node_modules/.pnpm/pouchdb-collate@7.2.2/node_modules/pouchdb-collate/lib/index.js' implicitly has an 'any' type.
      Try `npm i --save-dev @types/pouchdb-collate` if it exists or add a new declaration (.d.ts) file containing `declare module 'pouchdb-collate';`

即使在 collate/src 文件夹中已经有一个 global.d.ts 文件包含完全相同的语法,并且当文件夹中的 运行 脚本时它提供了正确的类型!

我只能通过在项目 B 中放置另一个 global.d.ts 的副本来解决这个问题。

作为替代方案,我尝试在包含 global.d.ts 的 monorepo 中创建一个包 C,并通过 index.ts 文件从 pouchdb-collate 重新导出符号,例如...

// modules/collate/src/index.ts
export { parseIndexableString, toIndexableString } from "pouchdb-collate";

这种方法(通过包别名)的好处是最终用在 typescript 中销售、重写和测试的版本替换这些函数。但是,这种方法存在同样的问题。

C 包如何重新导出该第三方包的符号和合适的类型,以便导入 C 包的项目可以使用它们?

对于我的案例,我成功地 re-exporting third-party 模块,输入如下。

首先,我在我的 monorepo 中创建了一个名为 @blabla/collate 的新模块,它以纯 javascript 的形式导入 re-exported,例如...

// src/index.js
module.exports = require("pouchdb-collate");

在它旁边我放置了一个名为 index.d.ts 的文件来声明我的新包的类型...

// src/index.d.ts
declare module "@blabla/collate" {
  export function toIndexableString(item: any): string;
  export function parseIndexableString(indexableString: string): any;
}

按照打字稿文档的建议,我将值添加到 @blabla/collatepackage.json 中,如下所示...

  "main": "src/index.js",
  "types": "src/index.d.ts",

所以这并没有直接键入 pouchdb-collate 包,而是通过正常的 javascript 机制 re-export,然后导出新 javascript 源文件的声明.

感觉应该有更优雅的方法,所以我不会将其标记为答案,以防万一有人做出贡献。