【问题标题】:Typescript : Method can be static打字稿:方法可以是静态的
【发布时间】:2017-08-20 11:50:17
【问题描述】:

打字稿 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;

Webstorm 检查警告

> 方法可以是静态的

提出了关于 getIndex() 函数:

但是

如果我把它改成静态的

公共静态getIndex()

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

我应该改变什么?

感谢反馈

【问题讨论】:

    标签: typescript static


    【解决方案1】:

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

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

    您可以在TypeScript Handbook 中找到有关static 的更多信息(请参阅“静态属性”部分)。

    【讨论】:

    • 根据这个答案link直接访问有问题......那么最佳做法是什么?我刚刚从成员中删除了所有“静态”,并通过注射修复了所有出现的问题啊哈,我应该恢复吗?
    • @TonySamperi 我同意这个答案,并在单例实例上使用依赖注入而不是静态方法。它使您的代码更易于测试以及该答案中描述的优势。不要太担心 TypeScript 暗示这些方法可以是静态的 - 依赖注入的单例实例只是静态类的替代解决方案,而且一点也不逊色。
    猜你喜欢
    • 2017-09-11
    • 1970-01-01
    • 2020-09-11
    • 2021-04-27
    • 2019-01-24
    • 2016-08-28
    • 1970-01-01
    • 2022-11-25
    相关资源
    最近更新 更多