I have the following typescript type:
type ItemTypes = (GameItem & { id: undefined }) | (CurrencyItem & { id: string });
The GameItem
is an object that doesn't have the "id" attribute so normally I would disambiguate like this in TS:
if (item.id !== undefined) {
// CurrencyItem
} else {
// GameItem
}
However in my svelte component if I try to do the equivalent TS complains that the value can be the other type:
{#if item.id !== undefined}
<!-- CurrencyItem expects item to be `CurrencyItem` so I get a "Type 'GameItem' is not assignable to type 'CurrencyItem'." -->
<CurrencyItem item={item} />
{:else}
<!-- GameItem expects item to be `GameItem` so I get a "Type 'CurrencyItem' is not assignable to type 'GameItem'." -->
<GameItem item={item} />
{/if}
Is there a way to avoid the error? Thanks.
{#if item.id !== undefined} <CurrencyItem item={item as CurrencyItem} /> {:else} <GameItem item={item as GameItem} /> {/if}
as
) is not supported