I'm new to Typescript and trying to figure out the syntax.
I have an Autocomplete React Component, which takes in a data prop, which is an array of objects of shape { label:string, value:string }. Relevant code from Autocomplete.tsx :
...
interface AutocompleteOption {
label: string;
value: string;
}
interface AutocompleteProps {
className?: string;
data: Array<object>;
icon?: string;
id?: string;
onChange?: Function;
}
...
const Autocomplete = ({ id = "", className = "", data = [], icon = "", onChange }: AutocompleteProps): ReactElement => {
...
return (
...
<div className={classnames("Autocomplete__values_list", isListVisible ? "active" : "")}>
{data.map((option: AutocompleteOption) => {
if (option.label.toLowerCase().includes(currentValue.toLowerCase())) {
return (
<button
className="Autocomplete__option"
key={`option_${option.value}`}
onClick={(e) => {
handleSelectOption(e, option.label);
}}>
{option.label}
</button>
);
}
})}
</div>
...
)
}
The line with {data.map((option: AutocompleteOption) => { gets highlighted in my IDE with the following error :
Argument of type '(option: AutocompleteOption) => JSX.Element | undefined' is not assignable to parameter of type '(value: object, index: number, array: object[]) => Element | undefined'.
Types of parameters 'option' and 'value' are incompatible.
Type '{}' is missing the following properties from type 'AutocompleteOption': label, value, keyts(2345)
What am I doing wrong ?
Thank you for your help !
CodePudding user response:
Please try to return something in the map, maybe that is the reason.
const Autocomplete = ({ id = "", className = "", data = [], icon = "", onChange }: AutocompleteProps): ReactElement => {
...
return (
...
<div className={classnames("Autocomplete__values_list", isListVisible ? "active" : "")}>
{data.map((option: AutocompleteOption) => {
if (option.label.toLowerCase().includes(currentValue.toLowerCase())) {
return (
<button
className="Autocomplete__option"
key={`option_${option.value}`}
onClick={(e) => {
handleSelectOption(e, option.label);
}}>
{option.label}
</button>
);
} else {
return null;
}
})}
</div>
...
)
}
CodePudding user response:
Somebody found the solution in a comment :
data: Array<object>; Did you mean to do data: Array<AutocompleteOption>? – Nicholas Tower
Thank you !
