逐步为第三方javascript模块添加类型



我刚刚被指派将一个相当大的项目从Javascript转换为Typescript。其中一个困难是,我们正在使用的第三方模块也是Javascript的,但理想情况下,我们也希望为其添加类型。这个第三方模块在整个代码库中被广泛使用,所以我们希望逐步添加这些类型。

那么,假设我们有两个这样的组件:

// -----| FirstComponentConsumer.tsx |-------------------------
import { FirstComponent } from 'third-party';
export const FirstComponentConsumer = () => {
return (
<FirstComponent name="pants" />
);
};
// -----| SecondComponentConsumer.tsx |------------------------
import { SecondComponent } from 'third-party';
export const SecondComponentConsumer = () => {
return (
<SecondComponent type="text" />
);
};

现在,我想为FirstComponent添加类型,但还没有为SecondComponent添加类型——我将在稍后添加这些类型(实际上有数百个导出需要键入)。所以我可以创建我的类型文件,像这样:

// types.d.ts 
import type { ReactNode } from 'react';
declare module 'third-party' {
export type FirstComponentProps = {
name?: string;
}
export const FirstComponent = (props: FirstComponentProps) => ReactNode;
}

这是预期的工作-FirstComponent现在键入!但是,它打破了SecondComponentConsumer,因为我没有说third-party模块导出SecondComponent:

Module '"third-party"' has no exported member 'SecondComponent'.  TS2305   

当然这很有意义,但是我可以关闭对"未声明类型"的检查吗?还是想要鱼与熊掌兼得?

这样做可能会奏效,基本上您只是导出所有内容,但具体键入单个组件。我还没有测试过,但我认为它应该可以工作。

declare module "third-party" {
const FirstComponent: (name?: string) => ReactNode;
type Exports = {
FirstComponent: typeof FirstComponent;
} & {
[key: PropertyKey]: any;
}
const exports: Exports;
export default exports;
export { FirstComponent };
}