javascriptsveltedestructuring

Destructure and don't destructure variable at the same time in svelte


I was wondering if it's possible to have access to entire object inside if/for, but still be able to destructure individual props

{#if object_var}
  {const {prop_var} = object_var}. <- doesn't work, "unexpected token"
  
  display: {prop_var}

{/if}

Solution

  • Without any leading symbol, the curly braces signal a text expression. You cannot use arbitrary JS there; regular declarations are not allowed.

    There is a @const tag that can be used in some specific places.
    Here this would work since the tag is an immediate child of #if:

    {#if object_var}
      {@const { prop_var } = object_var}
      display: {prop_var}
    {/if}