Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I use branch code based on TypeScript types in Svelte?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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");
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading