Skip to content

Typescript Classes compiles reactive variables into illegal state #15852

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
tertiusunaffi opened this issue Apr 30, 2025 · 3 comments
Closed

Comments

@tertiusunaffi
Copy link

Describe the bug

In Svelte 5, we can use reactive variables in classes.
You can also create 'reactive' files (example.svelte.js).
Combining these two ideas also works fine.

However, when I do the same thing in Typescript, it compiles into a broken state.

Reproduction

In file: +page.svelte:

<script> <!-- OR: <script lang="ts"> -->
	import { test } from './test.svelte';
</script>

In file test.svelte.ts:

class Test {
    something = $state()
}

export const test = new Test();

Note: It works fine doing the same with a JS file (text.svelte.js)

Logs

11:21:10 [vite] Internal server error: src/routes/test.svelte.ts:3:21 `$state(...)` can only be used as a variable declaration initializer or a class field
https://svelte.dev/e/state_invalid_placement
  Plugin: vite-plugin-svelte-module
  File: src/routes/test.svelte.ts:2:16
   1 |  class Test {
   2 |    constructor() {
   3 |      this.something = $state();
                                     ^
   4 |    }
   5 |  }

System Info

System:
    OS: Linux 6.8 Ubuntu 24.04.2 LTS 24.04.2 LTS (Noble Numbat)
    CPU: (16) x64 12th Gen Intel(R) Core(TM) i5-1240P
    Memory: 3.42 GB / 15.32 GB
    Container: Yes
    Shell: 5.2.21 - /bin/bash
  Binaries:
    Node: 22.14.0 - ~/.nvm/versions/node/v22.14.0/bin/node
    npm: 10.9.2 - ~/.nvm/versions/node/v22.14.0/bin/npm
  Browsers:
    Chrome: 128.0.6613.119
  npmPackages:
    svelte: ^5.28.2 => 5.28.2

Severity

annoyance

@7nik
Copy link
Contributor

7nik commented Apr 30, 2025

Looks like adding to the project tsconfig.json with "target": "ES2022" or higher fixes the problem.

@brunnerh
Copy link
Member

The correct configuration is documented in a section of the TypeScript docs.

@elliott-with-the-longest-name-on-github
Copy link
Contributor

Closing as this is just a misconfiguration

@elliott-with-the-longest-name-on-github elliott-with-the-longest-name-on-github closed this as not planned Won't fix, can't repro, duplicate, stale Apr 30, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants