1

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.

1 Answer 1

3

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);
    }
  }
}

Playground Link

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.