首页 > 解决方案 > 有没有办法创建具有设置类型参数和返回值的方法?

问题描述

我正在创建一个用于处理 Express 路线的模块。我创建了一个程序,它从目录中的类中调用方法。

该类的示例可以在这里看到。

class UsersController {
  private ping(_: any, response: Response) {
    response.status(200).send({ message: "Pong!" });
  }

  public get(): RouteDeclaration[] {
    return [{ path: "/ping", method: "get", action: this.ping }];
  }
}

我想知道是否有可能,例如用一些抽象类扩展类,这可以让我做一些类似 all 方法的通配符的事情:

abstract class RouteController {
  abstract get(): RouteDeclaration[];
  abstract *(request: Request, response: Response, next: NextFunction): void; // like this!
}

毕竟有可能以某种方式通配这些没有特定名称的方法吗?

标签: node.jstypescript

解决方案


我认为您可以使用这样的索引签名来实现它:

type Method = (req: Request, res: Response, next: NextFunction) => void;

abstract class RouteController {
  abstract get(): RouteDeclaration[];

  [key: string]: Method;
}

class UserController extends RouteController {
  private ping(_: any, response: Response) {
    response.status(200).send({ message: "Pong!" });
  }

  get() {
    return [{ path: "/ping", method: "get", action: this.ping }];
  }

  myMethod: Method = (req, res, next) => {
    // implementation
  };

  otherMethod: Method = (req, res, next) => {
    // implementation
  };

  // this will give a compiler error:
  illegalMethod(v: number): string {
    return "";
  }
}

我希望编译器自动推断类中方法的参数和返回类型UserController,但这似乎只适用于简单类型。这就是为什么最好将签名提取到类似的东西Method并将其用于方法实现的原因。当然你也可以让它们成为真正的方法,但是你必须为每个方法指定参数的类型和返回类型。


推荐阅读