![](/img/trans.png)
[英]How to use generics in props in React in a functional component?
[英]Is there a way to use generics to type a complex object array that accurately compares a React component and its props type?
我的團隊為我們正在使用的 API 創建了 typescript 類型定義,因此我們無法觸及源代碼,只能觸及定義。
我們有一個名為add
的函數,它本質上是在主程序中添加一個或多個 React 組件。 對象的props
屬性應該取決於component
屬性上列出的組件類型。
它看起來像這樣:
add(arg1, arg2, { //some other args children: [{ id: string1, //BackButton can be a functional or class-based component component: BackButton, //BackButtonProps will be defined within BackButton props: BackButtonProps }, { id: string2, //SkipButton can be a functional or class-based component component: SkipButton, //SkipButtonProps will be defined within SkipButton props: SkipButtonProps } ] });
作為參考,該函數有一個替代(重載)版本,它只添加一個組件,而不是多個我已經能夠找出打字稿的組件。 它看起來像這樣:
add<T>( id: string, component: ComponentType<T>, props: T ): void;
我的問題是——由於子組件的數量未知,我如何在add
函數上使用泛型,以便正確鍵入所有子組件( props
和component
屬性匹配)?
add
的通用簽名如下所示。
declare function add<T extends any[]>(arg1: any, arg2: any, arg3: {
children: [...{ [K in keyof T]: {
id: string,
component: T[K]
props: React.ComponentProps<T[K]>
}}]
}): void
泛型類型T
將存儲一個元組,其中每個元素都是一個反應組件。 對於傳遞數組的索引為K
的每個元素, component
類型將用作T[K]
中的類型,而props
類型必須是React.ComponentProps<T[K]>
。
讓我們看看它的實際效果:
const BackButton = (props: {a: string}) => {
return <div></div>
}
const SkipButton = (props: {b: string}) => {
return <div></div>
}
add(0, 0, {
children: [
{
id: "1",
component: BackButton,
props: { a: "123" }
},
{
id: "2",
component: SkipButton,
props: { b: "123" }
},
{
id: "3",
component: SkipButton,
props: { a: "123" } // Error: Type '{ a: string; }' is not assignable to type '{ b: string; }'
}
]
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.