14

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?

2 Answers 2

36

Edit: The design was changed, generics should now be defined as an attribute which uses the regular extends keyword:

<script lang="ts" generics="T extends { id: number }">

RFC


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>
Sign up to request clarification or add additional context in comments.

4 Comments

this is pretty useful information. I could not find anything on svelte docs but it works. Should I open an issue for that?
@sryscad It's still not completely finalized, see this
This isn't such an old question, so I'll try to answer a question: after defining generics="T", how do I enter a value for it when calling the component?
@Lucas: It's derived from usage. E.g. if you have export let value: T, the T will be whatever you put in when specifying <Component value={thing} />.
6

The answer by @brunnerh is already very good. But in order to have no eslint errors, the generic type T needs to be defined in typescript and not only the generics attribute of the <script>. This will hopefully change in the future.

<script lang="ts" context="module">
  type T = { id: number };
</script>

<script lang="ts" generics="T extends { id: number }">
  import type { Writable } from "svelte/store";
  export let store: Writable<T[]>;
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.