I have the following enum and state:
enum FilterId {
filter1,
filter2,
filter3,
filter4,
filter5,
}
type FiltersInComponent = { [key in FilterId]: boolean };
const [appliedFilters, setAppliedFilters] = React.useState<FiltersInComponent>()
Question 1: How do I initialise the appliedFilters state to (in short notation):
{
filter1: false,
filter2: false,
filter3: false,
filter4: false,
filter5: false
}
Question 2: How do I loop through appliedFilters and display a checkbox?
I have the following so far:
{Object.keys(appliedFilters)
.filter((v) => !isNaN(Number(v)))
.map((option) => {
const isChecked: boolean = appliedFilters[option];
return (
<>
<Checkbox checked={isChecked} />
<Typography>
{optionMessage(Number(option))}
</Typography>
</>
);
})}
But I'm getting the following error for appliedFilters[option]
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'FiltersInComponent'.
No index signature with a parameter of type 'string' was found on type 'FiltersInComponent'.
The problem is in the way you've defined this enum.
You're looking for something more along these lines:
type FilterId = 'filter1' | 'filter2' | 'filter3' | 'filter4' | 'filter5'
const foo = () => {
type FiltersInComponent = { [key in FilterId]: boolean }
const [appliedFilters, setAppliedFilters] =
React.useState<FiltersInComponent>({
filter1: false,
filter2: false,
filter3: false,
filter4: false,
filter5: false,
})
As you have it right now [key in FilterId] evaluates to
type FiltersInComponent = {
0: boolean;
1: boolean;
2: boolean;
3: boolean;
4: boolean;
}
as your enum values are the defaults of 0,1,2 etc. You could if you wanted, add enum values of 'filter1' etc and then use a string template literal to extract type FilterIdType = ${FilterId}; But if you're going to modify your enum and have control over it you're better off just going for the simpler union type.