Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

153
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda