Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How To Appropriately Type a Variable Using React's useState

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}
/>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading