I have defined this object in the TypeScript file and have use the following reduce() method and there is no issue with it.
sampleList = {
totalRecordsTest: {},
sampleList: [
{
parent: 'Sample Text 2',
children: [
{
id: 1,
text: "Sample Text 1"
},
],
},
{
parent: 'Sample Text 2',
children: [
{
id: 2,
text: "Sample Text 2"
},
],
},
{
parent: 'Sample Text 3',
children: [
{
id: 3,
text: "Sample Text 3"
},
],
},
]
}
let grouped = this.sampleList.sampleList.reduce((groups, current) => {
groups[current.parent] = groups[current.parent] || [];
groups[current.parent].push(...current.children);
return groups;
}, Object.create(null));
this.groupedSampleList = Object.keys(grouped).map((key) => ({
parent: key,
children: grouped[key],
}));
However, when I tried to create a model interface file for the "sampleList" in another file I am getting the error Type 'undefined' cannot be used as an index type in the following method for the current variable.
TypeScript File
let grouped2 = this.sampleList.reduce((groups, current) => {
groups[current.parent] = groups[current.parent] || [];
groups[current.parent].push(...current.children);
return groups;
}, Object.create(null));
Import model in TypeScript
sampleList: SampleList[] = []
Model File
export interface SampleListModel {
parent?: string | '-',
children?: ChildrenSampleModel[];
}
export class SampleList implements SampleListModel {
constructor(
public parent?: string | '-',
public children?: ChildrenSampleModel[]
) { }
}
export interface ChildrenSampleModel {
id?: number,
text?: string
}
export class ChildrenSample implements ChildrenSampleModel {
constructor(
public id?: number,
public text?: string
) { }
}
Solution
The parent
is declared as optional which is why it can be undefined and when I use it as an index it will throw the error "Type 'undefined' cannot be used as an index type in the following method for the current variable."
export interface SampleListModel {
parent: string,
children: ChildrenSampleModel[];
}
export class SampleList implements SampleListModel {
constructor(
public parent: string,
public children: ChildrenSampleModel[]
) { }
}
CodePudding user response:
It may be because parent
is optional in the constructor of SampleList
, so it can be undefined and you can use it as an index.