打字稿:方法可以是静态的

23 static typescript

typescript v 2.1.0

我写了以下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;
Run Code Online (Sandbox Code Playgroud)

Webstorm检查警告

>方法可以是静态的

关于getIndex()函数引发:

如果我把它改成静态

public static getIndex()

,我得到一个错误:类型'ServerRouter'上不存在TS2339'getIndex'

我应该改变什么?

谢谢你的反馈

Ben*_*ott 33

静态方法存在于而不是对象实例上.你将不得不改变this.getIndexServerRouter.getIndex你的init功能.

WebStorm建议如果方法不触及实例的任何状态,则使方法保持静态,因为它表明该方法存在于该类的所有实例的通用级别.

您可以staticTypeScript手册中找到更多相关信息(请参阅"静态属性"部分).