I am creating a module for handling Express routes. I have created a program, which calls methods from classes in directory.
Example of that class can be seen here.
class UsersController {
private ping(_: any, response: Response) {
response.status(200).send({ message: "Pong!" });
}
public get(): RouteDeclaration[] {
return [{ path: "/ping", method: "get", action: this.ping }];
}
}
I wonder if it's possible to, e.g extend the class with some abstract class, which could allow me do something like an all method's wildcard:
abstract class RouteController {
abstract get(): RouteDeclaration[];
abstract *(request: Request, response: Response, next: NextFunction): void; // like this!
}
Is it possible to somehow wildcard these methods with no specific name after all?
CodePudding user response:
It's not possible. Abstract methods should have a method signature, which implies on having a method name, to be implemented.
I suggest you to create a generic method name like execute
.
CodePudding user response:
I think you can achieve it with an index signature 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 "";
}
}
I expected the compiler to automatically infer the argument and return types for the methods in the UserController
class, but that only seems to work for simple types. That's why it seems best to extract the signature to something like Method
and use that for the method implementations. Of course you can also just make them real methods, but you will have to specify the types for the arguments and return type for each method.