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

Svelte components with generics

I want to use a generic type in a Svelte(Kit) component’s props, and I found out there is this type T = $$Generic thing:

<script lang="ts">
  import type { Writable } from "svelte/store";
  type T = $$Generic;
  export let store: Writable<T[]>;
</script>

While that is great, I do need slightly more information than that: I require that the T has a property id. Normally I’d do something like this:

export type WithId = { id: number };
function foo<T extends WithId>(property: T) { ... }

How can I do something similar for Svelte component props?

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

>Solution :

You can specify the type it extends like this:

type T = $$Generic<{ id: number }>;

You can also use type or interface names, though if you define them within a component, you might have to place them in the module script, i.e. something like this:

<script lang="ts" context="module">
    interface WithId { id: number }
</script>
<script lang="ts">
    export let store: Writable<T[]>;

    type T = $$Generic<WithId>;
</script>

RFC

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