I have a dropdown component with a callback onSelect:(option: string) => void
I'm using it as a sort picker in one application, where the options are of enum type:
enum SORT_OPTIONS {
LATEST = 'LATEST',
OLDEST = 'OLDEST'
}
const onSortSelect = (val: SORT_OPTIONS) => {...}
<MyDropdown onSelect={onSortSelect} ... />
And typescript complains:
Type '(val: SORT_OPTIONS) => void' is not assignable to type '(option: string) => void'.
Types of parameters 'val' and 'option' are incompatible.
Type 'string' is not assignable to type 'SORT_OPTIONS'. TS2322
It's a bit counter-intuitive but makes sense, since in MyDropdown
a string option
will be passed to the onSortSelect
callback, which requires an enum value.
Question is what is the best way to fix the types here? IMO both functions are typed correctly, onSelect
should accept any string since MyDropdown
can be used in any context. onSortSelect
should only accept SORT_OPTIONS
.
Currently I'm casting the type of onSortSelect: <MyDropdown onSelect={onSortSelect as (val:string) => void} ... />
but it feels quite verbose