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

函数返回匿名类时使用Decorators报错:Decorators are not valid here.ts(1206)

问题

尝试通过函数参数构建并返回匿名类时,遇到TypeScript错误:Decorators are not valid here.ts(1206)

错误截图

错误截图

代码示例

const ControllerTemplateBuilder = (newRoute:string)=>{
return class {    
    @route(newRoute)
    async getAll(req: Request, res: Response) {
        try {
            return res.status(200).json({ mesg: "helo" })
        } catch (error) {
            const { message } = error as Error;
            throw new Error(message);
        }
    }
}
}
解决方法

该错误源于TypeScript对匿名类成员装饰器的语法限制,可通过以下方式解决:

1. 为返回的类添加名称

给匿名类赋予一个明确的名称即可解除装饰器的语法限制:

const ControllerTemplateBuilder = (newRoute:string)=>{
return class GeneratedController {    
    @route(newRoute)
    async getAll(req: Request, res: Response) {
        try {
            return res.status(200).json({ mesg: "helo" })
        } catch (error) {
            const { message } = error as Error;
            throw new Error(message);
        }
    }
}
}

2. 验证TypeScript配置

确保tsconfig.json中已启用装饰器相关配置项:

{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "target": "ES6" // 需设置为ES6或更高版本
  }
}

若配置无误仍报错,优先使用第一种方案——为类添加名称是最直接的解决途径。

内容的提问来源于stack exchange,提问作者Luis Ricardo Legreaux Medina

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 22:56:30