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
Typescript : Method can be static
提问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.getIndex
to ServerRouter.getIndex
in your init
function.
静态方法存在于类而不是对象实例中。您必须在您的函数中更改this.getIndex
为。ServerRouter.getIndex
init
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 static
in the TypeScript Handbook(see the "Static Properties" section).
您可以static
在TypeScript 手册中找到更多信息(请参阅“静态属性”部分)。