Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

152
Vistas
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

    Property 'x' is missing in type...

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

or like this

export let x ?? 4.1658126;

or like this

export let x ?? MY_CONSTANT_VAR;
almost 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

do like this:

<script>
  export let x = 0;
</script>

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

now it will work in the parent without that error in the IDE

<main>
 <MyChild x={10} /> <!-- choosed value: 10 -->
 <MyChild />        <!-- choosed value: 0  -->
</main>

There is no need for ??, just use =

almost 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda