Paul
Paul

Reputation: 1441

event.target.value handle as ENUM

The event.target.value returns an 'String' value and I would like to have it recognized as an ENUM type. I have the following code:

export enum Permissions {
    OnlyMe,
    Everyone,
    SelectedPerson
}
...

<FormControl>
<InputLabel>Label name</InputLabel>
<NativeSelect
    value={state.user.permission}
    onChange={(event) =>
        setState({
        ...state,
        user: {
            ...state.user,
            permission: event.target.value as Permissions
        }
    })}
>
    <option value={Permissions.OnlyMe}>Only me</option>
    <option value={Permissions.Everyone}>Everyone</option>
    <option value={Permissions.SelectedPerson}>Selected persons</option>
</NativeSelect>

I get the typescript error "Conversion of type 'string' to Permissions may be a mistake because neither type sufficiently overlaps with the other."

I have already tried:

permission: Permissions(event.target.value) or

permission: Permissions(String(event.target.value))

but nothing is working. Thank you

Upvotes: 1

Views: 1642

Answers (1)

sh.alawneh
sh.alawneh

Reputation: 649

TypeScript will handle the enum as Number such as:

  • 0 for OnlyMe
  • 1 for EveryOne
  • 2 for SelectedPerson

event.target.value will return a string, so your problem is that you are trying to cast string to an integer you can simply do +event.target.value that will solve your compilation error by casting the string value using the js hack +.

Note: the solution above will return a number, in case you wish to get it as string you can do Permissions[+event.target.value]

Upvotes: 3

Related Questions