I used to employ an enum as a type because the following code is valid:
enum Test {
A,
B,
}
let a: Test = Test.A
However, when I use it as the type for React state, the IDE throws an error: Type FetchState is not assignable to type SetStateAction<FetchState.NULL>.
Here is what I’ve done:
const [ state, setState ]: [ FetchState, React.Dispatch<FetchState> ] = useState(FetchState.NULL)
I would like to determine whether my understanding is incorrect or if there is an issue with the code.
2
Answers
You have to set the generic type in the useState like this:
Working example here
If
FetchState
is anenum
andFetchState.NULL
is a valid member of thatenum
, the correct way to do this is simply:There’s no need for the explicit type annotation you have on the tuple.
You could also provide the type argument, but it’s not necessary in this case:
Playground link for both of those
But much of the time you don’t need to explicitly provide that type argument; TypeScript will infer it from the type of the initial value, such as in the above. In some cases, though, you may need to explicitly tell TypeScript what the type of the state member will be (usually because you’re using a union type). In that case, you’d include the type argument:
I’ve had to use the type argument there so TypeScript knows that
string
is a valid value forexample
, not justnull
.I was curious about supplying the tuple’s type. The type it gets by inference is
[FetchState, React.Dispatch<React.SetStateAction<FetchState>>]
(note that’s not quite the same as what you have in your question). Interestingly, though, if you provide that explicitly, you also have to provide the type argument touseState
explicitly, you can’t let TypeScript infer it. I have no idea why that is, but since as far as I know there’s never any need to provide the type annotation on the tuple, it’s academic.