How do I implement branch code using TypeScript types in Svelte?

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?

Answer №1

If you were working with TypeScript, this is how you would approach it:

function determineIfFolder(collectableOrFolder: Collectable | Folder): collectableOrFolder is Folder {
  return Object.hasOwn(collectableOrFolder, "folderName");
}

Next, in the context of Svelte:

{#if determineIfFolder(collectableOrFolder)}
  <div class="collectable">
    <img src={FolderSVG} alt={collectableOrFolder.folderName} crossOrigin="anonymous" class="shadow" />
  </div>
{:else}
  <CollectableThumb collectable={collectableOrFolder} />
{/if}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Updating color of an element in SVG and Angular2+ according to the background

In my svg element, I have a text element positioned after two rect elements. <svg id="floor-plan" width="300" height="100"> <rect width="300" height="100" fill="white"/> <rect width="50" height="50" fill="green"/> <text x="10" y="10" ...

Challenges with variable scopes and passing variables in Ionic 2 (Typescript)

In my Ionic 2 TypeScript file, I am facing an issue with setting the value of a variable from another method. When I close the modal, I get undefined as the value. I'm encountering difficulty in setting the value for coord. export class RegisterMapP ...

Dialog box obscuring PrimeNG dropdown menu

I'm working on an Angular2 app that utilizes PrimeNG components. My issue arises when trying to include a dropdown inside a dialog box. Despite my implementation, the dropdown ends up being cut off due to the constraints of the dialog box, as visible ...

Exploring the concept of union types and typeguards in TypeScript

I'm struggling with this code snippet: function test(): any[] | string { return [1,2] } let obj: any[] = test(); When I try to run it in vscode, I get the following error message: [ts] Type 'string | any[]' is not assignable to type & ...

What is the process for importing a TypeScript module from the local directory?

I am currently working on a TypeScript module with plans to eventually release it on NPM. However, before publishing, I want to import the module into another project hosted locally for testing purposes. Both projects are written in TypeScript. The TypeSc ...

Searching Local JSON Data in Ionic 4 with a Filter Input Bar

My current challenge involves filtering local JSON data in my Ionic project. Despite referencing other resources, I am unable to filter or display filtered items on the ngx-datatable. I suspect the issue may lie either in the filterItems function implement ...

Using TypeScript with Angular-UI Modals

Currently, my goal is to create a modal using angular-ui-bootstrap combined with typescript. To begin, I referenced an example from this link (which originally utilizes jQuery) and proceeded to convert the jQuery code into typescript classes. After succes ...

Validation Form Controls

Here is a piece of code that works for me: this.BridgeForm = this.formBuilder.group({ gateway: ["", [Validators.required, Validators.pattern(this.ipRegex)]], }); However, I would like to provide more detail about the properties: this.BridgeF ...

When setting a value that has been explicitly casted, the original literal type remains intact for the new property or variable

After defining the constant MODE with specific values, I noticed something interesting: const MODE = { NONE: 0 as 0, COMPLETED: 1 as 1, DELETED: 2 as 2 } as const // In a CreateReactApp project, enums aren't available It became appar ...

Extend the express request object with Typescript and then export the modified object

Seeking to enhance the Request object from express with custom fields using typescript. Based on this particular source, I created a file named @types/express/index.d.ts containing the following code : import { MyClass } from "../../src/MyClass" ...

Establishing the value of "document.cookie"

Encountering issues while trying to set a cookie using different methods: Method 1: document.cookie = name + "=" + value + "; expires=" + date.toUTCString() + "; path=/"; This method only sets the value up to "name=value" wh ...

Updating an array using `setState` does not result in the array being updated

I created a component that uses the .map() method to render an array of students and has a button to shuffle and update the display. However, I'm facing an issue where the display does not update every time I click the button. const Home: NextPage = ...

Steps to transfer extra files such as config/config.yaml to the .next directory

I have the following folder structure for my NextJS project: _posts/ components/ hooks/ config/ <--- includes config.yaml file for the server pages/ public/ .env.local ... yarn build successfully copies all dependencies except for the config/ folder. ...

Having Trouble with Angular Route (6) Configuration

I've been experiencing some unusual issues with the Angular 6 router, but this particular one is really frustrating. Here are the routes that I have defined in routing-app.module.ts: export const routes: Routes = [ { path: 'login&a ...

working with JSON arrays in angular framework

Is there a way to print a specific value from an array in typescript? Below is the code snippet in typescript that I'm working with: import { AngularFirestore } from '@angular/fire/firestore'; export class ProfileComponent implements OnInit ...

What method is most effective for combining two JSON files in Angular?

My data includes a json file with a product list that looks like this: [{"id":76, "name":"A", "description":"abc", "price":199, "imageUrl":"image.jpg", "productCategory":[{ "categoryId":5, "category":null },{ "categoryId":6, " ...

Difficulty Determining Literal Types that Expand a Union of Basic Data Types

Below are the components and function I am working with: interface ILabel<T> { readonly label: string; readonly key: T } interface IProps<T> { readonly labels: Array<ILabel<T>>; readonly defaultValue: T; readonly onChange ...

What is the best way to account for the 'elvis operator' within a given expression?

When connecting to my data from Firebase, I noticed that using the elvis operator is essential to avoid encountering undefined errors. Recently, as I delved into creating reactive forms, I encountered an issue with a component I developed that fetches actu ...

Application Initialization Error: appInits is not a valid function

When my Angular v17 application starts, I need to set some important values right away. This is how it's done in app.config.ts: export const appConfig: ApplicationConfig = { providers: [ ConfigService, ... { pr ...

Guide on transferring the token and user information from the backend to the front-end

Here is the code from my userservice.ts file export class UserService { BASE_URL = "http://localhost:8082"; constructor(private httpClient:HttpClient) {} public login(loginData:any){ return this.httpClient.post(this.BASE_URL+"/au ...