Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to declare props as optional in Svelte

I have created some components which take an optional prop like hide={true}. My problem is that these annoying error messages always flood my console when I don't pass that prop:

<MyComponent> was created without expected prop 'hide'

Is there some way to declare the props as optional?

like image 903
Gh05d Avatar asked Sep 10 '25 17:09

Gh05d


2 Answers

Just give them a default value.

MyComponent.svelte

<script>
  export let i = 123 // Default value is now 123
</script>

<!-- Output is "i = 123" -->
<p>i = {i}</p>

App.svelte

<script>
    import MyComponent from './MyComponent.svelte'
</script>

<!-- No error here! -->
<MyComponent/>

So, in your case you would change export let hide to export let hide = false.

like image 169
CherryDT Avatar answered Sep 12 '25 10:09

CherryDT


In some cases you don't want a default value so it's better to make the default null.

MyComponent.svelte

<script>
  export let myProp = null // Default value is null
</script>

<div class:has-some-prop={myProp}>
{#if myProp }
Has Prop: {myProp}
{:else}
No Prop
{/if}
</div>

App.svelte

<MyComponent/>
<MyComponent myProp='yep'/>

Result

<div>No Prop</div>

<div class:has-some-prop>
Has Prop<span>yep</span>
</div>

Update for Svelte 5 (3/7/24)

In Svelte 5 you declare your props with Runes like this:

let {hide} = $props(); // hide is undefined

For defaults:

let {hide=true} = $props();

With types you could do something like this:

interface ComponentProps {
  optional?: boolean;
  optionalWithDefault?: boolean;
  required: boolean;
}
let {optional, optionalWithDefault = true, required} = $props<ComponentProps>();

like image 37
jwerre Avatar answered Sep 12 '25 09:09

jwerre