Similar to Typescript: How to branch based on type but this is using Svelte, I am already using run-time type guards per that answer, and Svelte is still throwing errors.
I have an array named collectablesInFolders, of type Collectable | Folder.
Folders have a folderName property. Collectables don’t have a folderName. I have a runtime type check for this:
const isAFolder = (collectableOrFolder: Collectable | Folder) => {
return Object.hasOwn(collectableOrFolder, "folderName");
};
I am using the type check to branch my logic in Svelte:
{#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 gives an error that folderName doesn’t exist on Collectable items:
Property folderName does not exist on type.
That’s true, but that code is in a branch that’s only for items with a folderName key.
Likewise Svelte/TypeScript also gives an error that:
Type ‘{ collectableOrFolder: Collectable | Folder; }’ is not assignable to type ‘{ collectable: Collectable; }’.
That’s true as well, but that code is in a branch that’s only for items that don’t have a folderName key – ie Collectables.
I’ve tried using as but doing {collectableOrFolder.folderName as Folder} doesn’t seem to be allowed in Svelte HTML.
How can I use branch code based on TypeScript types in Svelte?
>Solution :
Although I am unsure if this will work in Svelte’s markup (I don’t know if the Svelte plug in will understand it), this is what you would do in TypeScript:
function isAFolder(collectableOrFolder: Collectable | Folder): collectableOrFolder is Folder {
return Object.hasOwn(collectableOrFolder, "folderName");
}