svelte: Allow @const inside an if block

Describe the problem

I want to make a {@const a = b} declaration inside an {#if cond} block, but svelte complains about it’s parent.

Describe the proposed solution

It would be cool if it just worked.

Alternatives considered

None

Importance

would make my life easier

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 5
  • Comments: 15 (9 by maintainers)

Most upvoted comments

This is supported now in 3.48.0.

Something like this (this is very similar to my use case):

<div>
  {#if selected.length == 1}
    {@const sel = selected[0]}
    <!-- some actions on this one -->
  {:else if selected.length == 0}
    none selected
  {:else}
    multiple selected
  {/if}
</div>

I arrived here from a searching for a related idea: Allowing “as” clauses on if, like with each.

It would be nice to have something like {#if expression as name}...{/if}.

This would be analogous to {#each expression as name}...{/each}.

As a workaround, can do something like: {#each f(expression) as name}...{/each} where f needs a better name and would be defined: const f = (x) => x == null ? [] : [x].

A example use for this would be something like: {#if path?.to?.container?.items as items}