Having an issue with my React + TypeScript application. I am trying to write a function to filter some data:
function matchesFilter(element: T, filter: Filters) {
const { name, options } = filter;
return options.filter(selected => selected).some(value => value === element[name]);
}
Using the generic type T for handling different formats of elements to be filtered.
This is how I defined Filters
:
export type Filter = {
name: string;
value: string;
selected: boolean;
};
export type Filters = {
name: string;
options: Filter[];
};
Encountering this error message:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'unknown'. No index signature with a parameter of type 'string' was found on type 'unknown'.ts(7053)
referring to element[name]
.
Seems like TypeScript is indicating that using type "string" (name
) as a key to access a property of object element
is problematic. How can I resolve this?
UPDATE: Sharing a more detailed version of the custom hook being developed, where the type is specified as a generic:
const useUpdateFilters = <T>(elements: T[], filterConfiguration: Filters[]) => {
const [filters, setFilters] = useState(filterConfiguration);
const [filteredObjects, setFilteredRequests] = useState<T[]>([]);
useEffect(() => {
function matchesFilter(element: T, filter: Filters) {
const { name, options } = filter;
return options.filter(selected => selected).some(value => value === element[name]);
}
function matchesAllFilters(element: T, filtersToMatch: Filters[]) {
return filtersToMatch.every(filterToMatch => matchesFilter(element, filterToMatch));
}
setFilteredRequests(elements.filter((element: T) => matchesAllFilters(element, filters)));
}, [filters, elements]);
return {
filters,
filteredObjects,
};
};
export default useUpdateFilters;