TypeScript类装饰器报错TS1238,请求代码修复方案
修复TypeScript类装饰器TS1238错误
错误原因
类装饰器的参数类型声明错误,Function类型无法匹配类构造函数的签名,TypeScript开启实验性装饰器后,对装饰器的类型检查有严格要求,因此抛出TS1238错误。
修复步骤
修正装饰器参数类型
将装饰器函数的参数类型从Function替换为new (...args: any[]) => any(通用类构造函数类型),或者更具体的typeof UserService(当前类的构造函数类型),让类型签名匹配。(可选)调整类属性定义
原代码中类的users是带初始值的实例属性,会覆盖装饰器在原型上设置的值。如果希望装饰器生效,可移除实例属性的初始值,或将其改为可选属性。
修复后的代码
interface IUserService { users: number; getUsersInDatabase(): number; } // 使用通用类构造函数类型作为参数 function nullUser(target: new (...args: any[]) => any) { target.prototype.users = 0; } @nullUser class UserService implements IUserService { // 移除初始值,使用原型上的users值 users: number; getUsersInDatabase(): number { return this.users; } } console.log(new UserService().getUsersInDatabase()) // 输出0
确认tsconfig配置
确保tsconfig.json中已正确配置以下选项:
{ "compilerOptions": { "target": "ES5", // 至少ES5版本,支持原型操作 "experimentalDecorators": true } }
内容的提问来源于stack exchange,提问作者sniks
相关产品推荐
相关产品推荐

