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

How can I fix my typescript type to work correctly?

How can I fix this Typescript type error that I’m getting?

Property 'original_title' does not exist on type 'Media'. and Property 'original_name' does not exist on type 'Media'.

I am getting data from an API and writing my own types for it. The API provides 2 different structures for Movies and TV Shows. TV Shows has name original_name origin country first_air_date and Movies has original_title release_date title video but both have a few other of the same properties so I wrote this type but am getting an error when using it.

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

I have a typescript type which looks like this:

export type Media = {
    adult: boolean;
    backdrop_path?: string;
    genre_ids: number[];
    id: number;
    original_language: string;
    overview: string;
    popularity: number;
    poster_path?: string;
    vote_average: number;
    vote_count: number;
} & (
    | {
            original_title: string;
            release_date: string;
            title: string;
            video: boolean;
      }
    | {
            first_air_date: string;
            name: string;
            origin_country: string[];
            original_name: string;
      }
);

However when trying to use it like this:

...
<View>
    {moviesData.results.map((result: Media) => (
        <Text key={result.id}>{result.original_title}</Text>
    ))}
</View>
<View>
    {showsData.results.map((result: Media) => (
        <Text key={result.id}>{result.original_name}</Text>
    ))}
</View>
...

>Solution :

For the porperties specific to Movie shows and TV shows, you have to do something like this

<View>
    {showsData.results.map((result: Media) => (
        <Text key={result.id}>{('original_title' in result) && result.original_title}</Text>
    ))}
</View>
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