简体   繁体   中英

Generic props : why are these types incompatible?

I have two React components with props taking a generic parameter TVariables . These props have the following fields: variables of type TVariables and setVariables of type (vars: TVariables) => void .

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. But I have an incompatibility error when setting setVariables .

This description is pretty obscure and the typescript error report is even more, so I created a minimalist codesandbox demo:

CodeSandbox link

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 .

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.

It seems like Typescript is complaining because of these 2 variables that you declared in your initial state

test: "demo",
sortOrder: -1,

If you add those to the ListVariables , the error disappears:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM