Home > Enterprise >  How to correctly type React useState hook with enum in TypeScript
How to correctly type React useState hook with enum in TypeScript

Time:11-05

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?

CodePudding user response:

Just set the type as Status.

const [isValid, setIsValid] = useState<Status>(ApiStatus.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

CodePudding user response:

If you tweek your enum keys to be the same as values, you can do this with keyof and typeof as follows:

import { useEffect, useState } from "react";
import "./styles.css";

export enum Status {
  pending = "pending",
  success = "success",
  error = "error"
}

export default function App() {
  const [st, setSt] = useState<keyof typeof Status>();

  useEffect(() => {
    setSt(Status.error);
  }, []);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

Link

  • Related