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

升级4.0.5至4.9.5后Decorator失效,类属性返回undefined求助

TypeScript 4.9.5 自定义装饰器失效问题解决

问题原因

你当前的装饰器是给类的原型(prototype)添加属性,但TypeScript 4.9.x版本对装饰器的类型检查和编译逻辑做了严格化调整;另外如果你的访问方式是直接通过类本身(而非实例)获取属性,也会返回undefined。旧版本中Function类型参数不够精确,也可能导致编译后属性绑定异常。

解决方案

根据你的需求(实例或静态类属性访问),调整装饰器代码:

1. 给实例添加可访问属性

如果需要通过类的实例获取tableName和tableDescription,修改装饰器为:

export function TableName(tableName: string, tableDescription: string) {
  return function<T extends new (...args: any[]) => {}>(constructor: T) {
    constructor.prototype.tableName = tableName;
    constructor.prototype.tableDescription = tableDescription;
    return constructor;
  };
}

使用示例:

@TableName('users', '用户表')
class User {}

const userInstance = new User();
console.log(userInstance.tableName); // 输出 'users'
console.log(userInstance.tableDescription); // 输出 '用户表'

2. 给类添加静态可访问属性

如果需要直接通过类本身(而非实例)获取属性,直接给构造函数赋值:

export function TableName(tableName: string, tableDescription: string) {
  return function<T extends new (...args: any[]) => {}>(constructor: T) {
    // 静态属性绑定到构造函数本身
    constructor.tableName = tableName;
    constructor.tableDescription = tableDescription;
    // 同时保留实例属性(如果需要)
    constructor.prototype.tableName = tableName;
    constructor.prototype.tableDescription = tableDescription;
    return constructor;
  };
}

使用示例:

@TableName('users', '用户表')
class User {}

console.log(User.tableName); // 输出 'users'
const userInstance = new User();
console.log(userInstance.tableName); // 输出 'users'

额外检查

确保你的tsconfig.json中开启了装饰器相关配置:

{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "target": "es2015"
  }
}

内容的提问来源于stack exchange,提问作者Jean Carlos dos Santos

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 18:33:19