Svelte 5 Optional snippets in components #10660
-
Hi, I have a question about snippets that come with Svelte 5. Is there a way to make snippets optional? I succeeded in making this work with the following solution, but I encountered an error in VSCode. Perhaps my approach is incorrect. My "solution"For instance, I have a Card component and I want to make the header and footer snippets optional: card.svelte<script lang="ts">
import type { Snippet } from 'svelte';
let {
header = null,
body,
footer = null
} = $props<{ header: Snippet; body: Snippet; footer: Snippet }>();
</script>
<div>
{#if header}
<div>
{@render header()}
</div>
{/if}
<div>
{@render body()}
</div>
{#if footer}
<div>
{@render footer()}
</div>
{/if}
</div> +page.svelte<Card>
{#snippet header()}
<p>My Card Header</p>
{/snippet}
{#snippet body()}
<p>My Card Body</p>
{/snippet}
</Card> Here, my solution appears to work because I can exclude the header or footer by not including the snippet inside the Card component. However, I encounter the following error:
The error message indicates that the footer property is expected but missing. Is my solution incorrect, or is this error irrelevant? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
The types "claim" that the snippets are required, change this: - } = $props<{ header: Snippet; body: Snippet; footer: Snippet }>();
+ } = $props<{ header?: Snippet; body: Snippet; footer?: Snippet }>(); (Would also not assign |
Beta Was this translation helpful? Give feedback.
The types "claim" that the snippets are required, change this:
(Would also not assign
null
, either leave it unassigned or useundefined
. Though with certain strict optionsundefined
will not be equivalent to unset; you may have to include it in the type asSnippet | undefined
.)