4

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?

Damien Monni
  • 1,418
  • 3
  • 15
  • 25
  • 1
    You need to convert your string to an enum, look at this: https://stackoverflow.com/questions/62821682/how-can-i-cast-a-string-to-an-enum-in-typescript – Ids van der Zee Jul 05 '21 at 10:58

3 Answers3

6

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.

Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
1

You can do this

setFilter(value as Category);
Deepinder Singh
  • 729
  • 10
  • 18
0

I tried the suggested solution and then typescript was not happy as follows:

Conversion of type 'string' to type 'Tab' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.

SOLUTION: was to change the value to a number so in this case:

setFilter(Number(value));
phildn
  • 134
  • 1
  • 5