typescriptsveltesvelte-component

Store Component Attributes in a strongly typed array


In svelte, I would like to strongly type an array to match the properties that a specific component exports.

So in the following example I would like const things = [] to know that each item within needs to have a name and an age property.

<script lang="ts">
  // Thing.svelte

  export let name: string;
  export let age: number;
</script>
<script lang="ts">
  // +Page.svelte

  import Thing from '$lib/Thing.svelte';

  const things = [{
    naem: "Bob",
    age: 36  
  }];
</script>

{#each things as thing}
  <Thing {...thing} />
{/each}

Note the typo "naem" should be "name", I would like intellisense to pick up on this because it knows that Thing.svelte needs a name and an age. Ideally I would like to do this without managing my own ThingOptions type.

Is that possible? Thanks.


Solution

  • Svelte exports utility types for this:

    import type { ComponentProps } from 'svelte';
    const things: ComponentProps<Thing>[] = [ ... ];