Looking for a solution similar to the one mentioned in Typescript: How to branch based on type, but tailored for Svelte. Despite implementing run-time type guards as suggested, Svelte continues to throw errors.
I am dealing with an array called collectablesInFolders
, containing elements of type Collectable | Folder
.
Folders
have a property named folderName
, while Collectables do not possess a folderName
. I have set up a runtime type check for this scenario:
const isAFolder = (collectableOrFolder: Collectable | Folder) => {
return Object.hasOwn(collectableOrFolder, "folderName");
};
To guide my logic in Svelte, I am utilizing this type check:
{#each collectablesInFolders as collectableOrFolder}
{#if isAFolder(collectableOrFolder)}
<div class="collectable">
<img src={FolderSVG} alt={collectableOrFolder.folderName} crossOrigin="anonymous" class="shadow" />
</div>
{:else}
<CollectableThumb {collectableOrFolder} />
{/if}
{/each}
Svelte/TypeScript raises an error indicating that folderName
does not exist on Collectable
items:
Property folderName does not exist on type.
While this is correct, the code is designed for items specifically with a folderName
key.
Additionally, another error arises stating:
Type '{ collectableOrFolder: Collectable | Folder; }' is not assignable to type '{ collectable: Collectable; }'.
Once again, this is intentional as the code pertains only to items lacking a folderName
key - or Collectables.
Attempts to use as
by writing
{collectableOrFolder.folderName as Folder}
seem to be disallowed in Svelte HTML.
How can I effectively branch code based on TypeScript types within Svelte?