簡體   English   中英

通用道具:為什么這些類型不兼容?

[英]Generic props : why are these types incompatible?

我有兩個帶有帶有通用參數TVariables的道具的 React 組件。 這些道具具有以下字段:類型TVariablesvariables和類型為(vars: TVariables) => void setVariables setVariables。

當我像這樣使用我的組件時:

const [variables, setVariables] = useState({ ...someProperties })

<A variables={variables} setVariables={setVariables}/>

我希望組件A能夠推斷出TVariables ,因此這兩個道具都可以工作。 但是設置setVariables時出現不兼容錯誤。

這個描述非常晦澀,而且 typescript 錯誤報告更多,所以我創建了一個極簡的代碼框演示:

代碼沙盒鏈接

為什么會出現這些錯誤,我該如何解決? 謝謝你。

您應該為 setVariables 使用類型React.Dispatch<React.SetStateAction<TVariables>> setVariables

Set state functions in React can passed the new value for the state variable, but can also be passed a callback function that updates the state variable. 因此類型(variables: TVariables) => void與 React 集 state function 的類型不匹配。

似乎 Typescript 抱怨因為您在初始 state 中聲明的這兩個變量

test: "demo",
sortOrder: -1,

如果將它們添加到ListVariables ,錯誤就會消失:

type ListVariables = {
  limit: number;
  page: number;
  test: string;
  sortOrder: number;
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM