I have the following interfaces:
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"
}
I know that if mediaType is equal to "movie" then data is always going to be of a custom type called Movie. I want my code to know this without casting or using as when using data.
I do not want to do something like this, if possible:
let docId = "";
if (mediaType === "movie") {
docId = (data as Movie).id.toString();
}
How can I shape this interface so 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 errors or warnings like Property 'show' does not exist on type '{ id: number; title: string; }'?
Propsa discriminated union, but right now the code here isn't quite a minimal reproducible example suitable for dropping into a standalone IDE like the TypeScript Playground (link). Could you edit the example code so that it demonstrates what you're seeing without unrelated errors (e.g.,mediaType,data,TMDB,IGDB, andTraktare not defined; could you either provide typings for them or change them?)