search

Home  >  Q&A  >  body text

How to fix typescript error when setting state to previous state in React?

I defined this state

const [userInfo, setUserInfo] = React.useState<UserInfo | undefined>()

Somewhere in my useEffect I try to set it based on the previous state.

So do this

setUserInfo(
                          (prevState) => {
                          return {
                              ...prevState,
                              ...someRef.current
                          }
                      })

But failed with the following error

Type error: Argument of type '(prevState: any) => any' is not assignable to parameter of type 'UserInfo'.
  Type '(prevState: any) => any' is missing the following properties from type 'UserInfo': name, age, gender

What's even weirder is that I updated the code to return the previous state. Basically this

setUserInfo((prevState) => return prevState)

This operation failed with the same error!

Type error: Argument of type '(prevState: any) => any' is not assignable to parameter of type 'UserInfo'.
  Type '(prevState: any) => any' is missing the following properties from type 'UserInfo': name, age, gender

I sincerely think this will work. I'm getting the previous state and returning it, but this doesn't compile.

If I disable the check and run the application it works as expected, so this looks like a typescript issue.

Any ideas on how to solve this problem?

P粉520545753P粉520545753336 days ago429

reply all(1)I'll reply

  • P粉770375450

    P粉7703754502024-02-04 14:04:52

    You can convert the return value to UserInfo.

    setUserInfo(
      (prevState) => {
        return {
          ...prevState,
          ...someRef.current
        } as UserInfo;
      }
    );

    reply
    0
  • Cancelreply