implement express controller class with typescript implement express controller class with typescript typescript typescript

implement express controller class with typescript


You need to use the bind function to keep the scope of this when the method is invoked:

let user = new User();router.get("/", user.test.bind(user));

Or you can do that in the User constructor:

export class User {    constructor() {        this.test = this.test.bind(this);    }    test(req, res, next) {        ...    }}

Another option is to use an arrow function:

let user = new User();router.get("/", (req, res, next) => user.test(req, res, next));


You can use export default and instantiate the controller so it can be used without instantiation in whichever file you've imported the controller.

register.controller.ts

import { Router, Request, Response, NextFunction } from 'express';class Register {    constructor() {          this.register = this.register.bind(this);    }    register(req: Request, res: Response, next: NextFunction) {      // ... removed for brevity    }}export default new Register();

server.ts or auth.routes.ts

import registerCtrl from '../controllers/auth/register.controller.js';// ... removed for brevityrouter.post('/register', registerCtrl.register);