将外部模块 TypeScript 声明公开给使用模块

Exposing external module TypeScript declarations to consuming modules

我有一个已发布的 TypeScript 模块(我们称它为 shared-stuff),该模块旨在由其他 TypeScript 模块导入。此 shared-stuff 模块具有第三方依赖项,这些依赖项没有 @types 范围的声明,因此该模块内部有几个声明文件:

/lib/declarations/
  something.d.ts
  another-thing.d.ts

这些声明文件在 shared-stuff 的上下文中工作正常。但是,一旦消费应用程序开始从 shared-stuff 导入,TypeScript 就会给我这样的错误:

Could not find a declaration file for module 'another-thing'.

我可以通过让消费者明确地从依赖项中导入 .d.ts 文件来解决这个挑战,但这并不理想,因为每个消费者都必须做同样的事情。

有没有办法让一个消费模块 "inherit" 来自依赖项的声明?

Is there a way to have a consuming module "inherit" the declarations from a dependency?

常规方法是将其作为 peerDepenency 并在您的文档中提及它需要使用,例如对于 react

npm i shared-lib react @types/react

也就是您带来自己的 react / @types/react

版本

由于您的消费者(shared-stuff 的消费者)依赖于 another-thing 的类型,您也需要导出它们。

一种方法是在您的 index.ts 中使用 /// <reference>(并记住将您的 /lib/declarations 包含在您的发行版中。

另一种方法是不依赖外部类型。即,而不是做:

import { SomeType } from 'another-thing'
export function foo(): SomeType { ... }

自己定义类型(在 shared-stuff 中,而不是在 another-thing.d.ts 中):

export type SomeType = { ... }
export function foo(): SomeType { ... }

理论上,another-thing 中的类型应该遵循库本身的语义版本,但实际上它更容易发生重大变化。

一个原因是该库一开始并不是用 TypeScript 编写的,因此库作者可能会在不知情的情况下不小心破坏了类型。

因此,虽然与重用类型相比,自己声明类型听起来很脆弱,但事实并非如此。 (在您的情况下,无论如何您都是自己定义它们)。

只要确保你有一套好的测试来捕捉任何类型的重大变化。