skip to Main Content

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


  1. You have to set the generic type in the useState like this:

    const [ state, setState ]: [ FetchState, React.Dispatch<FetchState> ] = useState<FetchState>(FetchState.NULL)
    

    Working example here

    Login or Signup to reply.
  2. If FetchState is an enum and FetchState.NULL is a valid member of that enum, the correct way to do this is simply:

    const [state, setState] = useState(FetchState.NULL);
    

    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:

    const [state, setState] = useState<FetchState>(FetchState.NULL);
    

    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:

    const [example, setExample] = useState<string | null>(null);
    

    I’ve had to use the type argument there so TypeScript knows that string is a valid value for example, not just null.


    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 to useState 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search