Search code examples
reactjstypescriptreact-hookstypescript-typings

How to correctly type React useState hook with enum in TypeScript


How to type my useState hook correctly?

I have this enum type:

export enum Status {
  PENDING = 'pending',
  SUCCESS = 'success',
  ERROR = 'error',
}

And the useState hook: const [isValid, setIsValid] = useState<// What to add here>(ApiStatus.PENDING);

So that the value of the useState hook can only be one of the Status values?


Solution

  • Just set the type as Status.

    const [isValid, setIsValid] = useState<Status>(Status.PENDING)
    
    // valid
    setIsValid(Status.PENDING)
    setIsValid(Status.SUCCESS)
    setIsValid(Status.ERROR)
    

    If you also want to allow passing the string values, wrap Status into a template literal type.

    const [isValid, setIsValid] = useState<`${Status}`>(Status.PENDING)
    
    // valid
    setIsValid(Status.PENDING)
    setIsValid(Status.SUCCESS)
    setIsValid(Status.ERROR)
    setIsValid("pending")
    setIsValid("success")
    setIsValid("error")
    

    Playground