Reputation: 303
I have an object two layers deep that I'm trying to loop over:
const sections: object = {sectionA: {density1: "content_1"}, sectionB: {density1: "content_1"}
function makeSectionGrid(sections: object){
const sectionGrid: JSX.Element[] = []
for (let section in sections){
for (let density in section){
let content: string = section[density]
sectionGrid.push(<div>{content}</div>)
}
}
}
The TypeScript compiler complains about for (let density in section)
:
The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'string'
Am I supposed to cast section? I've tried that, and it isn't working. Not sure how to make the error go away.
Upvotes: 1
Views: 403
Reputation: 4352
You may want to add some interfaces:
interface SectionInterface {
[density: string]: string;
}
interface SectionsInterface {
[key: string]: SectionInterface;
}
const sections: SectionsInterface = {
sectionA: { density1: "content_1" }, sectionB: { density1: "content_1" }
}
function makeSectionGrid(sections: SectionsInterface) {
const sectionGrid: any[] = []
for (let section in sections){
for (let density in sections[section]){
let content: string = sections[section][density];
sectionGrid.push(content);
}
}
}
Upvotes: 3