[英]Generic props : why are these types incompatible?
我有两个带有带有通用参数TVariables
的道具的 React 组件。 这些道具具有以下字段:类型TVariables
的variables
和类型为(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.