5

I am trying to make a login form in react with typescript. But setEmail method is not accepting value. It says Argument of type 'string' is not assignable to parameter of type 'SetStateAction'. What should I do to solve it?

enter image description here

2
  • 1
    You need to add a default string value to the hook above. [email,setEmail] = useState('') Commented Feb 1, 2021 at 12:52
  • See Also: Set types on useState React Hook with TypeScript Commented Jun 17, 2021 at 21:12

4 Answers 4

14
+250

You can set a string type for it

Explicit way:

const [email, setEmail] = useState<string>('')

or Implicit way:

const [email, setEmail] = useState('')

or if you want to set number type

const [inputNumber, setInputNumber] = useState<number>(0);

then in jsx, do it this way

<input
  type="number"
  value={inputNumber}
  onChange={(val) => {
    //Some ways to do this
    setInputNumber(Number(val.target.value));
    setInputNumber(+val.target.value);
    setInputNumber(parseInt(val.target.value,0));
  }}
/>

see more examples

Sign up to request clarification or add additional context in comments.

1 Comment

This does not work for me.
2

you just need to use generic in this case with useState hook

simple case

const [email, setEmail] = useState<string>("")

complex case

  • declare an interface
     interface IUser{
        email:string
        }
  • make useState generic
     const [email, setEmail] = useState<IUser>({email: ''})

you can see DefinitelyTyped

Comments

1

Without any initial argument, the type of email and setEmail will be undefined.

const [email, setEmail]: [undefined, (value: ((prevState: undefined) => undefined) | undefined) => void] = useState();

So the first step is to enforce email to be a string by either using useState("") or even better useState<string>("").

Comments

1

Initialize the useState with an empty string will solve.

useState can infer the type based on your initialState, thats why initialize with empty string will solve your case.

useState without initialState will be undefined, so your type and state is undefined.

If you want your state to have an more complex type, you need to pass a initialState with defined type:

const initialState: TYPE = {
  // ...
};
const [state, setState] = useState(initialState);

or

Pass the type to useState without set type to initialState, like: useState<TYPE>(initialState);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.