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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43052041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:39:06  来源:igfitidea点击:

Typescript : Method can be static

typescriptstatic

提问by Ben Elliott

typescript v 2.1.0

打字稿 v 2.1.0

I wrote the following ServerRouter.ts

我写了以下 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

Webstorm 检查警告

> Method can be static

> 方法可以是静态的

is raised about the getIndex() function :

是关于 getIndex() 函数的:

BUT

If I changed it to static

如果我把它改成静态

public static getIndex()

公共静态 getIndex()

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

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

What should I change ?

我应该改变什么?

thanks for feedback

感谢反馈

回答by Ben Elliott

A static method exists on a classrather than an object instance. You would have to change this.getIndexto ServerRouter.getIndexin your initfunction.

静态方法存在于而不是对象实例中。您必须在您的函数中更改this.getIndex为。ServerRouter.getIndexinit

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 allinstances of that class.

WebStorm 建议将方法设为静态,如果它们不涉及实例的任何状态,因为它表明该方法存在于对该类的所有实例通用的级别。

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

您可以staticTypeScript 手册中找到更多信息(请参阅“静态属性”部分)。