Home > Enterprise >  "Abstract classes" in Svelte
"Abstract classes" in Svelte

Time:11-16

I am fairly new to Svelte and frontend (I mostly have experience with Rust/C /Python), please excuse me if this is a dumb question.

I am trying to display different types of time-indexed data and I have a variable "timestamp" that the user can edit. I want to display the matching item for each of my lists for a given timestamp.

Let's say my lists are temperature readings and rainfall readings.

interface Temperature {
temperature: number
}
interface Rainfall {
rainfall: number
}
A = [{"timestamp" : 0, "temperature": 20}, {"timestamp": 1, "temperature": 25}, {"timestamp" : 2, "temperature": 28}]   
B = [{"timestamp" : 0, "rainfall": 200}, {"timestamp" :1, "rainfall": 210}, {"timestamp": 2, "rainfall": 220}]

I have Svelte components Temperature and Rainfall that can display the corresponding Typescript interfaces. I don't know how I can abstract over the fact that each type of data has a timestamp and a way how it is displayed as a Svelte component. In an OO language, I would use something like an abstract class that has a display() method that would return the corresponding Svelte component.

Is there a way in Svelte/JS to write unified code for selecting the datum matching a timestamp from a list and then display that datum with its corresponding Svelte component?

Many thanks

CodePudding user response:

You could add a property for the component to display the data and then show it using <svelte:component>. Though, if the data comes from a server, you cannot pass the component like that.

I would probably use a mapping via a type property instead. E.g.

interface Temperature {
  type: 'temperature';
  temperature: number;
}
interface Rainfall {
  type: 'rainfall';
  rainfall: number;
}

type Datum = Temperature | Rainfall;
<script lang="ts">
  // ...
  import TemperatureComponent from '...';
  import RainfallComponent from '...';

  export let item: Datum;

  const displayMapping: Record<Datum['type'], SvelteComponent> = {
    temperature: TemperatureComponent,
    rainfall: RainfallComponent,
  }
</script>

<svelte:component this={displayMapping[item.type]} {...item} />

Alternatively you could just use an {#if}/{:else if} chain based on the type.

  • Related