Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using enum for event.target.value in Typescript and React

I have an enum defining categories that can be selected via a form radio inputs:

enum Category {
  PRACTICAL = 'practical',
  POSITIONING = 'positioning',
}

How can I use this enum in my radio group onChange handler function? This is what I am currently doing:

const [filter, setFilter] = useState<Category>(Category.POSITIONING);

const handleFilterClick = (event: React.ChangeEvent<HTMLInputElement>) => {
  const { value } = event.target;
  setFilter(value); // <== Argument of type 'string' is not assignable to parameter of type 'SetStateAction<Category>'
};

setFilter(value) is not working because typeof value is string instead of Category.

How should I handle this situation?

like image 925
Damien Monni Avatar asked Sep 07 '26 16:09

Damien Monni


1 Answers

Typescript has no way to determine that event.target.value will be a member of that enum. So you will need to use a type assertion to tell typescript that you know those are the only possible values:

setFilter(value as Category);

Be aware that type assertions mean you're telling typescript not to check your work. If the JSX you've written actually has a way to set a value outside the enum, typescript will not be able to tell you about this.

like image 132
Nicholas Tower Avatar answered Sep 10 '26 05:09

Nicholas Tower



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!