TypeScript 5.4.5中Vite项目@State装饰器报错的解决咨询
Vite项目中TypeScript访问器装饰器报错
错误信息
Unable to resolve signature of property decorator when called as an expression. The runtime will invoke the decorator with 3 arguments, but the decorator expects 2.ts(1240) Decorator function return type is 'ClassAccessorDecoratorResult<unknown, unknown>' but is expected to be 'void' or 'any'.ts(1271)
相关代码
function State<This, Return>( target: ClassAccessorDecoratorTarget<This, Return>, _context: ClassAccessorDecoratorContext<This, Return> ) { const result: ClassAccessorDecoratorResult<This, Return> = { get(this: This) { return target.get.call(this); }, set(e: any) { target.set.call(this, e) }, }; return result; } class GlobalStore { constructor() { } @State accessor username = 'test' setUsername(data: string): void { this.username = data } getUsername(): string { return this.username } }
tsconfig.json配置
{ "compilerOptions": { "target": "ES2020", "useDefineForClassFields": true, "module": "ESNext", "lib": ["ES2020", "DOM", "DOM.Iterable"], "skipLibCheck": true, /* Bundler mode */ "moduleResolution": "bundler", "allowImportingTsExtensions": true, "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, /* Linting */ "strict": true, "noUnusedLocals": true, "noUnusedParameters": true, "noFallthroughCasesInSwitch": true }, "include": ["src"] }
解决方案
问题核心是TypeScript在Vite项目中误将新版访问器装饰器识别为旧版属性装饰器——旧版装饰器要求接收3个参数,而你定义的是符合ES2022标准的新版访问器装饰器,仅需2个参数。
修复步骤:
- 调整tsconfig.json配置
- 将
target升级为ES2022或更高版本(访问器装饰器是ES2022的标准特性) - 明确关闭旧版装饰器实验特性(添加
"experimentalDecorators": false) - 同步更新
lib数组,加入ES2022
- 将
修改后的tsconfig.json:
{ "compilerOptions": { "target": "ES2022", "useDefineForClassFields": true, "module": "ESNext", "lib": ["ES2022", "DOM", "DOM.Iterable"], "skipLibCheck": true, "moduleResolution": "bundler", "allowImportingTsExtensions": true, "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "strict": true, "noUnusedLocals": true, "noUnusedParameters": true, "noFallthroughCasesInSwitch": true, "experimentalDecorators": false }, "include": ["src"] }
- 确认TypeScript版本
执行npm ls typescript检查项目本地安装的TypeScript版本是否为5.4.5,确保Vite使用项目本地版本而非全局版本。
内容的提问来源于stack exchange,提问作者Erdem Ün
相关产品推荐
相关产品推荐

