Issue
Below is my code.
const [enteredAge, setEnteredAge] = useState<number | "">("");
Have defined the type for useState as number. Having a type like <number | undefined>
makes sense that we definig the type to be number
or undefined
. But in the above given code I have defined <number|"">
this way. Does this mean only initial state of the useState
can be defined ""
this way?
Solution
With useState<number | "">("");
your state will be initially set to ""
and then can either be set to a number or "" again but not any other string.
You can also initialise it to a number useState<number | "">(42);
the same way.
const [state, setState] = useState<number | "">("");
const [stateNum, setStateNum] = useState<number | "">(42);
setState("Foo"); // Error: Argument of type '"Foo"' is not assignable to parameter of type 'SetStateAction<number | "">'.ts(2345)
setState(0); // OK
setState(""); // OK
Answered By - Antoine Gagnon
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.