@State
给出错误。错误就在这里。我该如何解决这个错误。我正在使用 typescript 5.4.5
版本。
我正在使用 vite-web 项目。这个文件在src目录下。如果你尝试 typescript playgorund 没问题。但我的 vite 项目出现错误
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) {
// console.log(e)
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,
/* Decorators */
"experimentalDecorators": true,
"emitDecoratorMetadata": true
},
"include": ["src"]
}
你可以在这里看到 -> https://stackblitz.com/edit/vitejs-vite-haafpu?file=src%2Fstore.ts
"experimentalDecorators": true,
这意味着您没有使用 Typescript 5.0 中引入的新装饰器语法。
参见: https://www.typescriptlang.org/tsconfig/#experimentalDecorators。
装饰器标准有一个旧的实现,但它并没有通过这个过程成为真正的 JavaScript 功能。 Typescript 很早就采用了该标准,并且很多人都在使用它。然后标准就演变了。
Typescript 5.0 引入了一种新的装饰器语法,它更接近 Javascript 本身支持的语法。
启用
experimentalDecorators
会让您选择使用 older 装饰器语法。但您正在用新语法编写装饰器。