Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript -> a dynamic response from an API how to type

I am consuming an api that returns nested json. It is dynamic so the keys will often be different. What can be guaranteed is that the key and value will always be a string.

Here is an example:

const response = {
  name: 'Pete',
  location: 'London',
  age: {
    year: '21'
  }
}

I have tried type it like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

type Response = {
    [key: string]: string
}

Then in a React component I want to use it like this:

type Response = {
    [key: string]: string
}

const Foo = ({ data }: Response) => {
   return <pre>{JSON.stringify(data, null, 2)}</pre>
}

This gives me the following error:

Property ‘x’ does not exist on type ‘string’

Can anyone point me in the right direction here?

here is a link to stackblitz – https://stackblitz.com/edit/react-ts-4n7vcy?file=App.tsx

>Solution :

What you are doing is assigning the type Response to the props argument of your Foo functional component. So actually, the Foo component accepts a props object with the type of Response, but the data variable is inferred as a string by typescript. What you should do instead is;

interface IFooProps{
  data: Response;
}

const Foo = (props: IFooProps) => {
  return <pre>{JSON.stringify(props.data, null, 2)}</pre>;
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading