sveltejs / svelte

web development for the rest of us
https://svelte.dev
MIT License
79.65k stars 4.22k forks source link

Svelte 5: typescript Error when naming a variable "state" while previously $state rune is used. #13715

Open HighFunctioningSociopathSH opened 1 week ago

HighFunctioningSociopathSH commented 1 week ago

Describe the bug

a variable named "state" or "derived" can cause typescript to show error if the $state or $derived runes are used before that variable.

Reproduction

In the docs I ran into the following code:

<script lang="ts">
  let state = $state({ value: 0 });
  let derived = $derived({ value: state.value * 2 });
</script>

After trying to use it, I got an error and apparently its because I had used $state before. so the following code:

<script lang="ts">
  let something = $state("something");
  const somethingElse = $dervied(something);
  let state = $state({ value: 0 });
  let derived = $derived({ value: state.value * 2 });
</script>

will show an error saying "Block-scoped variable '$state' used before its declaration." or "Block-scoped variable '$derived' used before its declaration." It goes away if you change the name of the "state" or "derived" variables to something else. Svelte for VS code is on version 109.1.0

Logs

No response

System Info

System:
    OS: Windows 11 10.0.22631
    CPU: (16) x64 12th Gen Intel(R) Core(TM) i7-12650H
    Memory: 7.54 GB / 15.63 GB
  Binaries:
    Node: 20.12.2 - C:\Program Files\nodejs\node.EXE
    npm: 10.9.0 - C:\Program Files\nodejs\npm.CMD
    bun: 1.1.3 - ~\.bun\bin\bun.EXE
  Browsers:
    Edge: Chromium (129.0.2792.52)
    Internet Explorer: 11.0.22621.3527

Severity

annoyance

MotionlessTrain commented 1 week ago

This is intended When you have a variable with a particular name, the rune with that name is automatically disabled, to allow for the store subscription syntax That is, svelte can't make sure state is not a store, and reserves $state for the case it is one, and so that rune is automatically turned off

HighFunctioningSociopathSH commented 1 week ago

if so then maybe it should show a better error message that is less confusing. perhaps something that tells the user to avoid using variables with these names at runes mode. And perhaps change the names in the docs as well to avoid confusion.