Below are the interfaces I am working with:
interface Movie {
id: number;
title: string;
}
interface Show {
title: string;
ids: {
trakt: number;
imdb: string;
tmdb?: number;
};
}
interface Props {
data: Movie | Show;
inCountdown: boolean;
mediaType: "movie" | "tv"
}
If the media type is set to "movie", then the data
object will always be of type Movie
. I want my code to understand this without requiring explicit casting or using as
.
I would like to avoid doing something like this, if possible:
let docId = "";
if (mediaType === "movie") {
docId = (data as Movie).id.toString();
}
How can I structure this interface so that I can use
let mediaType = "movie"
let data = {id: 1, title: "Dune"}
let docId = "";
if (mediaType === "movie") {
docId = data.id.toString();
}
if (mediaType === "tv") {
docId = data.show.ids.trakt.toString();
}
without encountering errors or warnings such as
Property 'show' does not exist on type '{ id: number; title: string; }'
?