After creating a SelectBox component using react-select and applying onChange event to it, I encountered an issue. I wanted to include a type "SelectedItemType" to the selected option in the onChange event, but the property of onChange was defined as (property) onChange?: ((newValue: unknown, actionMeta: ActionMeta) => void) | undefined. This resulted in the option type being unknown, making it challenging to extract object attributes from the option.
import { ForwardedRef, forwardRef } from "react";
import Select, { SelectInstance } from "react-select";
export type SelectedItemType = {
value: string;
label: string;
};
export type SelectProps = {
options: SelectedItemType[];
ref?: ForwardedRef<SelectInstance>;
onChange: (selectedItem: unknown) => void;
};
const SelectBox: React.FC<SelectProps> = forwardRef<
SelectInstance,
SelectProps
>(({ options, onChange, ...props }, ref) => {
return (
<Select
options={options}
ref={ref}
{...props}
onChange={(newValue: unknown) => onChange(newValue)}
/>
);
});
export default SelectBox;
In the above code snippet, my aim was to add SelectedItemType to the newValue for onChange. However, I encountered an error stating that Type '(newValue: SelectedItemType) => void' is not assignable to type '(newValue: unknown, actionMeta: ActionMeta) => void'. The types of parameters 'newValue' were found to be incompatible, with 'unknown' not matching with 'SelectedItemType'. How can I successfully integrate this custom Type to the option in order to extract the value and label?