[英]How to “import” a 3rd party javascript module to my react project?
[英]Progressively add types for a 3rd party javascript module
我剛剛負責將一個相當大的項目從 Javascript 轉換為 Typescript。 困難之一是我們正在使用的第 3 方模塊之一也在 Javascript 中,但理想情況下,我們也希望為此添加類型。 這個第 3 方模塊在整個代碼庫中廣泛使用,因此我們希望逐步添加類型。
所以,假設我們有兩個這樣的組件:
// -----| 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
YET - 我稍后會添加這些類型(實際上需要輸入數百個導出)。 所以我可以創建我的類型文件,例如:
// 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 };
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.