Search code examples
javascriptsvelte

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?


Solution

  • 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.