How to fix typescript error when setting state to previous state in React?
P粉520545753
P粉520545753 2024-02-03 22:41:43
0
1
425

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粉520545753
P粉520545753

reply all(1)
P粉770375450

You can convert the return value to UserInfo.

setUserInfo(
  (prevState) => {
    return {
      ...prevState,
      ...someRef.current
    } as UserInfo;
  }
);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template