Issue
I have the following variable:
const sorting: Record<string, { filters: [], appliedFilters: [], search: string }> = {};
And I want to initialize it as following:
export let tableData: { props: (string | { name: string, ... })[] };
tableData.props.forEach((item) => {
if(typeof item === 'string') {
sorting[item].filters = [];
sorting[item].appliedFilters = [];
sorting[item].search = '';
} else {
sorting[item.name].filters = [];
sorting[item.name].appliedFilters = [];
sorting[item.name].search = '';
}
});
But when I run the it I get the following error:
TypeError: Cannot set properties of undefined (setting 'filters')
It might be worth noting that I am using Svelte and this code is ran inside a component where tableData
is an atribute, although I don't think this would change anything
I have already tried setting the type of the variable to object and that doesn't work. Does anyone know how I can fix this without resorting to any
type
Solution
This has nothing to do with typescript. sorting
is an empty object so sorting[item]
or sorting[item.name]
is always undefined.
You need to first define sorting[item]
before defining the properties within it.
sorting[item] = {
filters: [],
appliedFilters: [],
search: ''
};
The following would be a more accurate type description for the sorting
object.
const sorting: Record<string, { filters: [], appliedFilters: [], search: string } | undefined> = {};
Answered By - alexwbt
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.