[英]Generic props : why are these types incompatible?
I have two React components with props taking a generic parameter TVariables
.我有两个带有带有通用参数
TVariables
的道具的 React 组件。 These props have the following fields: variables
of type TVariables
and setVariables
of type (vars: TVariables) => void
.这些道具具有以下字段:类型
TVariables
的variables
和类型为(vars: TVariables) => void
setVariables
setVariables。
When I use my component like this:当我像这样使用我的组件时:
const [variables, setVariables] = useState({ ...someProperties })
<A variables={variables} setVariables={setVariables}/>
I would expect component A
to infer TVariables
, and so both props to work.我希望组件
A
能够推断出TVariables
,因此这两个道具都可以工作。 But I have an incompatibility error when setting setVariables
.但是设置
setVariables
时出现不兼容错误。
This description is pretty obscure and the typescript error report is even more, so I created a minimalist codesandbox demo:这个描述非常晦涩,而且 typescript 错误报告更多,所以我创建了一个极简的代码框演示:
Why do I have these errors, and how could I solve them?为什么会出现这些错误,我该如何解决? Thank you.
谢谢你。
You should use the type React.Dispatch<React.SetStateAction<TVariables>>
for setVariables
.您应该为 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. 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. Thus the type
(variables: TVariables) => void
does not match the type of a React set state function.因此类型
(variables: TVariables) => void
与 React 集 state function 的类型不匹配。
It seems like Typescript is complaining because of these 2 variables that you declared in your initial state似乎 Typescript 抱怨因为您在初始 state 中声明的这两个变量
test: "demo",
sortOrder: -1,
If you add those to the ListVariables
, the error disappears:如果将它们添加到
ListVariables
,错误就会消失:
type ListVariables = {
limit: number;
page: number;
test: string;
sortOrder: number;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.