Home > front end >  How To Appropriately Type a Variable Using React's useState
How To Appropriately Type a Variable Using React's useState

Time:02-10

How would I appropriately type variables in useState?

Below, basically alert needs to be "success" | "warning" | "error" | "info"

const [alertValue, setAlertValue] = useState("error");

<TextField
   label="Error State"
   message="this is an ERROR message"
   alert={alertValue} // error: Type 'string' is not assignable to type "success" | "warning" | "error" | "info";
   onChange={handleChange}
/>

CodePudding user response:

The useState hook is a generic function. You can supply the type when you call it. For example:

type AlertStatus = "success" | "warning" | "error" | "info"

const [alertValue, setAlertValue] = useState<AlertStatus>("error");

You should use the same property type defined for the alert property of the TextField component.

  • Related