programing

유형 스크립트: 메서드는 정적일 수 있습니다.

instargram 2023. 7. 1. 08:01
반응형

유형 스크립트: 메서드는 정적일 수 있습니다.

typescript v2.1.

저는 다음과 같은 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;

웹스톰 검사 경고

> 메서드는 정적일 수 있습니다.

getIndex() 함수에 대해 발생합니다.

그렇지만

정적으로 변경한 경우

public static getIndex()

오류 발생: TS2339 'getIndex'가 'ServerRouter' 유형에 없습니다.

무엇을 바꿔야 합니까?

피드백 감사합니다.

정적 메서드가 개체 인스턴스가 아닌 클래스에 있습니다.당신은 옷을 갈아입어야 할 것입니다.this.getIndex로.ServerRouter.getIndex당신의init기능.

WebStorm은 메소드가 해당 클래스의 모든 인스턴스에 일반적인 수준으로 존재함을 시사하므로 메소드가 인스턴스의 상태를 전혀 건드리지 않는 경우 메소드를 정적으로 만들 것을 제안합니다.

에 대해 자세히 알아볼 수 있습니다.staticTypeScript Handbook("정적 속성" 섹션 참조)에 있습니다.

언급URL : https://stackoverflow.com/questions/43052041/typescript-method-can-be-static

반응형