Skip to content

Typescript Classes compiles reactive variables into illegal stateΒ #15852

@tertiusunaffi

Description

@tertiusunaffi

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

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