Home > Back-end >  Simplify the typescript interface for fetched data from api
Simplify the typescript interface for fetched data from api

Time:05-17

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?

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

CodePudding user response:

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.

  • Related