Typescript : Method can be static

2019-04-18 03:39发布

问题:

typescript v 2.1.0

I wrote the following ServerRouter.ts

import {Router, Request, Response, NextFunction} from 'express';

export class ServerRouter {
  router: Router;

  /**
   * Initialize the ServerRouter
   */
  constructor() {
    this.router = Router();
    this.init();
  }

  /**
   * GET index page
   */
  public  getIndex(req: Request, res: Response, next: NextFunction) {
    res.render('index');
  }

  /**
   * Take each handler, and attach to one of the Express.Router's
   * endpoints.
   */
  init() {
    this.router.get('/', this.getIndex);
  }

}

// Create the ServerRouter, and export its configured Express.Router
const serverRouter = new ServerRouter().router;
export default serverRouter;

Webstorm inspection warning

> Method can be static

is raised about the getIndex() function :

BUT

If I changed it to static

public static getIndex()

, the I get an error : TS2339 'getIndex' does not exist on type 'ServerRouter'

What should I change ?

thanks for feedback

回答1:

A static method exists on a class rather than an object instance. You would have to change this.getIndex to ServerRouter.getIndex in your init function.

WebStorm suggests making methods static if they don't touch any of the state of an instance, since it suggests that the method exists at a level that is general to all instances of that class.

You can find out more about static in the TypeScript Handbook (see the "Static Properties" section).