You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Svelte 5中TypeScript类字段使用$state报错问题咨询

Svelte 5中TypeScript类字段使用$state报错问题

我定义了如下类:

class TestClass {
    prop = $state('test');
}

这段代码在.svelte.js文件以及带有<script lang="js">的.svelte文件中可正常运行,但在.svelte.ts文件和带有<script lang="ts">的.svelte文件中无法运行,报错如下:

CompileError: $state(...) can only be used as a variable declaration initializer or a class field

请问是操作有误,还是Svelte 5目前暂不支持在TypeScript类字段中使用$state?

我的tsconfig.json内容如下:

{
  "extends": "./.svelte-kit/tsconfig.json",
  "compilerOptions": {
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "module": "es2020",
    "lib": ["es2020", "dom"],
    "target": "es2019",
    "importsNotUsedAsValues": "error",
    "isolatedModules": true,
    "resolveJsonModule": true,
    "sourceMap": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "baseUrl": ".",
    "allowJs": true,
    "checkJs": true,
    "paths": {
      ....
    }
  },
  "include": [
    ....
  ],
  "exclude": ["node_modules/*"]
}

问题解析与解决办法

这不是你的操作问题,Svelte 5在TypeScript环境下,目前确实还不支持在类字段中直接使用$state。

原因在于:Svelte 5的响应式语法(如$state)在JavaScript中可以直接作为类字段初始化器,但TypeScript的类型检查逻辑会把$state识别为普通函数调用,再加上Svelte编译器对TypeScript文件中类字段位置的$state转换逻辑还未完善,就出现了这种矛盾的报错。

临时解决办法:

  • 在类的构造函数中声明$state变量,再挂载到实例属性上:
class TestClass {
    prop: string;

    constructor() {
        const prop = $state('test');
        this.prop = prop;
    }
}
  • 优先在Svelte组件的<script lang="ts">块内直接使用响应式声明,避免在自定义类中用$state。

后续可以关注Svelte 5的官方更新,等正式版或后续测试版发布后,类字段使用$state的TypeScript支持应该会被完善。

内容的提问来源于stack exchange,提问作者Stanislau Listratsenka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 04:24:55