函数返回匿名类时使用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
相关产品推荐
相关产品推荐

