简体   繁体   中英

How to Create an Instance of the Class without “new” Keyword

This project is NodeJS project with TypeScript.

I want to create an instance of App class. But, if I use new keyword, I have to pass constructor parameter.

The problem is that constructor parameter should be passed with dependency injection. So, I can't use new keyword to create an instance.

// Express
import { application as app } from 'express';

// Controllers
import { UserController } from './controllers/user.controller'

export class App {
  constructor(userController: UserController) {
    console.log("App is running");
    console.log("UserController url path is : ", userController.getUrlPath);

    this.run();
  }

  run(): void {
    app.listen(3000, function () {
      console.log('App is running on port 3000!');
    });
  }

  check(): void {
    console.log("working well");
  }
}

const appInstance: App = <App>Object.create(App.prototype); // it is not creating

console.log( appInstance.check() ); // ==> 'undefined'

This seems to go against the very concept of using classes
If you need to avoid passing a concrete UserController for testing purposes, you can use some form of mock.
Another option is to use a variable of type any :

const app = new App({} as any);

Depending on your tsconfig.json configuration, it should work (obviously you won't be able to access any of the functions/fields of the UserController object, but the construction of App should work just fine.
The last option (I could think of at least) is using a setter function for the UserController :

export class App {
 private _userController: UserController;
 get userController(): UserController {
  return this._userController;
 }
 set userController(ctrl: UserController) {
  this._userController = ctrl;
 }
}

And this way, after setting up a full DI infrastructure, you can use App.userController = SOME_USER_CONTROLLER_FROM_DI

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM