I'm trying to reuse a generic inside a function body, but I'm getting an error, why is this happening?
Example:
type OptionsArray<T> = T[]
type Option = {
name: string
}
// Why I get error here if OptionValueType contain name prop?
const filterName = <OptionValueType,>(options:OptionsArray<OptionValueType>) => options.map(el=>el.name)
export const filterOptions = <OptionValueType,>(options: OptionsArray<OptionValueType>, filterBy: string) : OptionsArray<OptionValueType> => {
if (filterBy === '') {
return [...options];
} else {
const filteredOptions = filterName<OptionValueType>(options);
return [...filteredOptions];
}
};
filterOptions<Option>([{name: 'Alex'}], 'name')
Is there any way to use generic types inside functions?
CodePudding user response:
You did not give your generic type a constraint:
const filterName = <OptionValueType extends Option>(options: OptionsArray<OptionValueType>) => options.map((el) => el.name);