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

Simplify the typescript interface for fetched data from api

I want to fetch movie data from omdbapi.

I’m trying to embed typescript to determine the exact data I get from the endpoint (I’m new to typescript).

The structure of the obtained data looks something like this, is it really necessary to list all the data individually in the interface if it is a string?

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

interface Movie {
  Title: string;
  Year: string;
  Rated: string;
  Released: string;
  Runtime: string;
  Genre: string;
  Director: string;
  Writer: string;
  Actors: string;
  Plot: string;
  Language: string;
  Country: string;
  Awards: string;
  Poster: string;
  Ratings: [
    {
      Source: string;
      Value: string;
    },
    {
      Source: string;
      Value: string;
    },
    {
      Source: string;
      Value: string;
    }
  ];
  Metascore: string;
  imdbRating: string;
  imdbVotes: string;
  imdbID: string;
  Type: string;
  DVD: string;
  BoxOffice: string;
  Production: string;
  Website: string;
  Response: string;
}

>Solution :

This sounds like a job for Record:

type Movie = Record<"Title" | "Year" | "... more keys here ..." | "Website" | "Response", string> & {
  Ratings: {
    Source: string;
    Value: string;
  }[];
};

Give it a union of all the keys that map to strings, and then intersect (combine) the record with an object type that holds the type for Ratings.

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