Correct way to type nullable state when using React's useState hook
Currently, the TypeScript compiler thinks the type of email
and password
are null
(and no other value). You can resolve this by providing an explicit type parameter to the useState
call so that the types of email
and password
are known to be string
or null
.
const { useState } = React;
function Example() {
const [state, setState] = useState<{email: null | string, password: null | string}>({ email: null, password: null });
function setEmail(email: string) {
setState(prevState => ({ ...prevState, email }))
}
return <p>{state.email}</p>
}
This is addressed in a few spots already:
https://dev.to/busypeoples/notes-on-typescript-react-hooks-28j2
https://codewithstyle.info/Using-React-useState-hook-with-TypeScript/
TLDR: pass a type argument to setState when you have an empty initial state
eg:
const [email, setEmail] = useState<string>();