menu

Questions & Answers

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?

Answers(2) :

Just make the default value 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>

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.

Comments:
2023-01-18 23:10:05
Yeah, I also thought of that workaround. Seems to be the only way currently.
2023-01-18 23:10:05
I don't see that as a workaround. See, you have a component that expects a property (and does not have a default) and you don't pass one. Then you have a good chance that the app will not work correctly. Each component should define defaults for the properties and work even if none as passed. If you can't assign default values to properties, then check those error messages for missing props or throw an error is component is mounted without a required prop.
2023-01-18 23:10:05
Correct — it's not a workaround, it's how it's designed to work
2023-01-18 23:10:05
Ok, if that was the intention then I will declare default props in the future. Thanks for the explanation.