I'm trying to create a route in Express using TypeScript, and so I, as usual, set the arguments of createUser
function to req
: Request
, res
: Response
and next
: NextFunction
, from @types/express
, obviously. It worked every time, but this time it shows an error:
No overload matches this call.
Overload 1 of 3, '(path: PathParams, ...handlers: RequestHandler<ParamsDictionary, any, any, ParsedQs>[]): Router', gave the following error.
Argument of type '(req: Request, res: Response, next: any) => Promise<any>' is not assignable to parameter of type 'RequestHandler<ParamsDictionary, any, any, ParsedQs>'.
Types of parameters 'req' and 'req' are incompatible.
Type 'Request<ParamsDictionary, any, any, ParsedQs>' is missing the following properties from type 'Request': cache, credentials, destination, integrity, and 15 more.
Overload 2 of 3, '(path: PathParams, ...handlers: RequestHandlerParams<ParamsDictionary, any, any, ParsedQs>[]): Router', gave the following error.
Argument of type '(req: Request, res: Response, next: any) => Promise<any>' is not assignable to parameter of type 'RequestHandlerParams<ParamsDictionary, any, any, ParsedQs>'.
Type '(req: Request, res: Response, next: any) => Promise<any>' is not assignable to type 'RequestHandler<ParamsDictionary, any, any, ParsedQs>'.
Overload 3 of 3, '(path: PathParams, subApplication: Application): Router', gave the following error.
Argument of type '(req: Request, res: Response, next: any) => Promise<any>' is not assignable to parameter of type 'Application'.
Type '(req: Request, res: Response, next: any) => Promise<any>' is missing the following properties from type 'Application': init, defaultConfiguration, engine, set, and 61 more.
How to fix that? Here's some code of the app:
protected setupRoutes(): void {
this.router.post("/", this.createUser);
}
// Routes:
private async createUser(req: Request, res: Response, next): Promise<any> {
try {
res.status(200).send("Hi!");
} catch (err) {
return next({
status: err.status,
message: err.message,
});
}
}
I am surprised this worked for you at all. Express has it's own types available for the request and the response that extend the base types you are using.
For instance, here is the type definition of the express request:
interface Request<P = core.ParamsDictionary, ResBody = any, ReqBody = any, ReqQuery = core.Query> extends core.Request<P, ResBody, ReqBody, ReqQuery> { }
Try using those types:
import express from 'express';
const handleMyRequest = (req: express.Request, res: express.Response) => {
// Whatever
}