1

Assume I have a JSON payload that parses into something like this

{
  "status": "123",
  "totalResults": 1234,
  "articles": [
    {
      "source": {
        "id": "123",
        "name": "123"
      },
      "author": "123",
      "title": "123",
      "url": "123",
      "imgUrl": "123",
      "publishedAt": "123",
      "content": "123"
    },
]
}

How would I set up the definition of the Example interface to model that the value of the items property is an object whose keys are strings and whose values are defined by the Item interface:

interface Item {
    status: string;
    totalResults: number;
    id: string
    name: string
    author: string
    title: string
    description: string
    url: string
    urlToImage: string
    publishedAt: string
    content: string
}

interface Example extends Item{
    articles: Array<Object>;
    source: {
     [key: string]: Item
    };
}


const example: Example = {
  "status": "123",
  "totalResults": 1,
  "articles": [
    {
      "source": {
        "id": "123",
        "name": "123"
      },
      "author": "123",
      "title": '123',
      "description": "123",
      "url": "123",
      "urlToImage": "123",
      "publishedAt": "123",
      "content": "123"
    },
  ]
}

2 Answers 2

2
export interface Reference{
  status:string,
  totalResults: number,
  articles: 
    {
      source: {
        id: string,
        name: string
      },
      author: string,
      title: string,
      url: string,
      imgUrl: string,
      publishedAt: string,
      content: string
    }[]
}
Sign up to request clarification or add additional context in comments.

1 Comment

I would like to suggest to add to the answer some extra explanation/comment - not code only
1

Here is a properly typed version, but I'm not sure if that is what you're looking for.

interface Item {
    status: string;
    totalResults: number;
    articles: Array<Articles>;
}

interface Articles {
    source: Source // or source: { id: string; name: string };
    author: string;
    title: string;
    description: string;
    url: string;
    urlToImage: string;
    publishedAt: string;
    content: string;
}

interface Source {
    id: string;
    name: string;
}

const example: Item = {
    "status": "123",
    "totalResults": 1,
    "articles": [
    {
        "source": {
            "id": "123",
            "name": "123"
        },
        "author": "123",
        "title": '123',
        "description": "123",
        "url": "123",
        "urlToImage": "123",
        "publishedAt": "123",
        "content": "123"
    },
    ]
}

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.