Search code examples
reactjstypescript

React Typescript - Argument of type is not assignable to parameter of type


I have a demo here

It's a React app using Typescript and hooks to capture entries into form that are simple displayed below.

Here in Stackblitz it works but locally I am using VS code and I get an error for setUser(userData); the error is

const userData: {
    username: string;
    password: string;
    prevState: null;
}
Argument of type '{ username: string; password: string; prevState: null; }' is not assignable to parameter of type '(prevState: null) => null'.
  Type '{ username: string; password: string; prevState: null; }' provides no match for the signature '(prevState: null): null'.ts(2345)

How can I fox this typescript error


Solution

  • const [user, setUser] = useState(null);
    

    Since you haven't given this a type, typescript has to try to infer it. It sees you passed in a null, so it assumes this state is (and always will be) null. Instead, you need to specify the type, as in:

    interface UserData {
      username: string;
      password: string;
      prevState: null
    }
    
    //...
    const [user, setUser] = useState<UserData | null>(null);