How to type props in Svelte 5?

Asked about 1 month ago Modified about 1 month ago Viewed 7 times

I understand that in Svelte 4 and previous versions props are individually declared using export let name: type = defaultValue;.

For example in Svelte 4:

<script lang="ts">
    export let name: string;
    export let gender: "male" | "female";
    export let alive: boolean = true;
</script>
// ...

I'm also aware of the new $props rune in Svelte 5, however I don't understand how I can type the props using this rune so that consumers of my component know what to expect (and for my own sanity when working with props inside the component).

Svelte 5:

<script lang="ts">
    // Not obvious to me where to add type definitions
    let {
        name,
        gender,
        alive = true
    } = $props();
</script>
// ...
0
s
69
1 Answer
Sort by
Accepted by Author Posted about 1 month ago

In Svelte 5, the $props rune returns component props as properties of an object. As such, to define the types of individual properties you have to create an object type and type its properties in accordance with your component props.

Inline

This is useful if your props are simple, and will not be used across multiple components.

<script lang="ts">
    let {
        name,
        gender,
        alive = true
    }: {
        name: string;
        gender: "male" | "female";
        alive: boolean;
    } = $props();
</script>
// ...

Explicit Definition

You can also define a separate interface or type, and use it to type your props. This can be especially useful if you want to utilize the prop component in multiple different components/files.

<script lang="ts">
    interface PersonProps {
        name: string;
        gender: "male" | "female";
        alive: boolean;
    };

    let {
        name,
        gender,
        alive = true
    }: PersonProps = $props();
</script>
// ...
0

Your Answer

You Must Log In or Sign Up to Answer Questions