Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decorators is not valid when returning a class on a function?

Basically I am trying to build a class on base a some parameters that are given on the function args, but returning it as anonymous class, but the error 'Decorators are not valid here.ts(1206)'.

Error

error picture

Code example

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);
        }
    }
}

}

like image 945
Luis Ricardo Legreaux Medina Avatar asked Oct 19 '25 10:10

Luis Ricardo Legreaux Medina


1 Answers

Decorators are not allowed in class expressions. You can easily work around this by defining the class, then returning it:

const ControllerTemplateBuilder = (newRoute:string)=>{
    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);
            }
        }
    };

    return _;
};
like image 101
catgirlkelly Avatar answered Oct 22 '25 01:10

catgirlkelly