![](/img/trans.png)
[英]React prop types with TypeScript - how to have a function type?
[英]How to set typescript type for prop value that takes in unique union types in React
嘗試為 prop 值設置類型,但不太確定如何 go 這樣做,因為類型是字符串聯合,根據使用 React 組件的位置而有所不同。
這是我的 typescript 接口。
interface IProps {
tabs: {
label: string;
tabId: string;
}[];
onClick: (tabId: string) => void;
}
React 組件在我的應用程序中的多個不同位置使用。 這里有兩個不同的例子。
const toggleTabs = (type: 'share' | 'home' | 'settings' ) => setActiveTab(type);
<Tabs onClick={toggleTabs} />
第二個例子
const toggleTabs = (type: 'history' | 'shopping' ) => setActiveTab(type);
<Tabs onClick={toggleTabs} />
但是,這給了我以下錯誤,因為 typescript 字符串類型不等於上面的字符串聯合類型。
Type 'string' is not assignable to type '"history" | "shopping"
由於我為每個實現使用不同的字符串聯合,我不確定將其設置為什么類型。
您可能想嘗試使用泛型參數:
interface IProps<Tabs extends string> {
tabs: {
label: string;
tabId: string;
}[];
onClick: (tabId: Tabs) => void;
}
在您通常使用IProps
的地方,您將參數添加到:
function Tabs<T extends string>(props: IProps<T>) {
然后每當你使用組件時,都會自動推斷類型:
<Tabs tabs={[]} onClick={(tab: "history" | "shopping") => tab} />
// ^ Tabs<"history" | "shopping">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.