I have a CARD type that can be either a TEXT_CARD or an IMAGE_CARD:
declare type TEXT_CARD = {
type: "paragraph" | "h1" | "h2";
text: string;
};
declare type IMAGE_CARD = {
type: "img";
src: string;
orientation: "portrait" | "landscape";
};
declare type CARD = TEXT_CARD | IMAGE_CARD;
When displaying a card, I need to switch between these two to render separate components.
<!-- index.svelte -->
<script lang="ts">
import TextCard from "./TextCard.svelte";
import ImageCard from "./ImageCard.svelte";
export let card: CARD;
</script>
{#if ["paragraph", "h1", "h2"].includes(card.type)}
<TextCard {card} />
{:else}
<ImageCard {card} />
{/if}
<!-- TextCard.svelte -->
<script lang="ts">
export let card: TEXT_CARD;
</script>
<h1>{card.text}</h1>
<!-- TextCard.svelte -->
<script lang="ts">
export let card: IMAGE_CARD;
</script>
<h1>{card.src}</h1>
However, TypeScript is now throwing an error in index.svelte, saying that CARD is not assignable to TEXT_CARD.
Type 'CARD' is not assignable to type 'TEXT_CARD'.
How and where should I assert that I am certain I am dealing with a TEXT_CARD / IMAGE_CARD? Or should I restructure my types from the beginning?