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

TypeScript类装饰器报错TS1238,请求代码修复方案

修复TypeScript类装饰器TS1238错误

错误原因

类装饰器的参数类型声明错误,Function类型无法匹配类构造函数的签名,TypeScript开启实验性装饰器后,对装饰器的类型检查有严格要求,因此抛出TS1238错误。

修复步骤

  1. 修正装饰器参数类型
    将装饰器函数的参数类型从Function替换为new (...args: any[]) => any(通用类构造函数类型),或者更具体的typeof UserService(当前类的构造函数类型),让类型签名匹配。

  2. (可选)调整类属性定义
    原代码中类的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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 16:33:18