how to make exported variable be optional in svelte.js framework?

let’s say I want to have a custom attribute where I can get some information from the parent element.

in svelte is easy, the syntax is like this:

MyChild.svelte

<script>
  export let x;
</script>

<div>choosed value: {x}</div>

MyParent.svelte

<main>
 <MyChild x={10} />
</main>

but let’s say I didn’t want to always pass the attribute value

<MyChild x={10} />
<MyChild /> <!-- this time I don't want to pass the value -->

I want if I don’t pass the value then it will use a secondary value.

in react we have ?? or ||,

  • but in svelte don’t seem to work
  • seems mandatory

enter image description here

so svelte tell me the problem before compiling

  • which is safe and good
  • but in my case,
    • I want to create 1 attribute that is mandatory,
    • and other 5 optional (not important, in most case are repetitive so this is why are optional)

is there a workaround?


so I want something like

export let x ?? 0;
// get "x" if you find an attribute
// then set the variable "x" to "x"

// but if the user doesn't add the attribute uses the second value "??"
// same as if x is undefined/null

??: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator