Issue
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?
Solution
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.
Answered By - Nicholas Tower
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.