Skip to content

error when redeclaring variables with var #14590

@leonidaz

Description

@leonidaz

Describe the bug

I'm working on a function that takes a parameter and either creates a signal variable with $state() or $state.raw().

However, the only way to do this for the same variable is to use var. However, this doesn't work because Svelte complains that variable has already been declared. This is perfectly allowed in Javascript of course. Obviously, it's not a good practice in general but in terms of being able to declare signal for the same variable this would be the only way currently.

<script>
  function doSomething (init, type = 'deep') {
    if (type === 'raw') {
      var myState = $state.raw(init);
    } else {
      var myState = $state(init)
    }

    // .......
  }
</script>

Error compiling
`myState` has already been declared

Ideally, I'd like to be able to use a ternary operator to assign. Wonder if this can be identified in the parser...

<script>
  let myState = type === 'raw' ? $state.raw(init) : $state(init);
</script>

It seems the only way to accomplish this is to have two signal variables and resort to using if conditions when reading or updating them which is quite annoying.

Reproduction

Playground reproduction

Logs

No response

System Info

Playground

Severity

annoyance

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions