node.js - 有没有办法创建具有设置类型参数和返回值的方法?
问题描述
我正在创建一个用于处理 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!
}
毕竟有可能以某种方式通配这些没有特定名称的方法吗?
解决方案
我认为您可以使用这样的索引签名来实现它:
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
并将其用于方法实现的原因。当然你也可以让它们成为真正的方法,但是你必须为每个方法指定参数的类型和返回类型。
推荐阅读
- azure-data-factory - 如何在 Azure 数据工厂的 CI/CD 管道上设置参数?
- python - Python:如何找到具有连接间隔开始和结束的最长连续间隔
- facebook - Bot 未启动消息 - Facebook 集成
- unity3d - Unity Buttons:非矩形
- scala - 带有 Tapir 的 json 中的状态字段
- facebook - 发布我的应用程序后,如何在我的 google play 控制台上更改应用程序内容描述?
- javascript - 检查指针是否与 OpenLayers 中的集群子特征相交?
- android - 通知图标的正确路径应该是什么?
- html - 具有固定宽度元素的 Flexbox
- apache-kafka - 无法找到或加载主类 org.apache.kafka.connect.cli.ConnectStandalone