node.js - Propiedades de ruta de Express en TypeScript
Estoy intentando crear una ruta en Express usando TypeScript, y como de costumbre, establecí los argumentos de la función createUser en req: Request, res: Response y next: NextFunction, de @types/express, obviamente. Funcionaba siempre, pero esta vez muestra un 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.
¿Cómo arreglar eso? Aquí hay un código de la aplicación:
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,
});
}
}
Respuesta #1
Me sorprende que esto haya funcionado para ti en absoluto. Express tiene sus propios tipos disponibles para la solicitud y la respuesta que extienden los tipos base que estás usando.
Por ejemplo, aquí está la definición de tipo de la solicitud de express:
interface Request<P = core.ParamsDictionary, ResBody = any, ReqBody = any, ReqQuery = core.Query> extends core.Request<P, ResBody, ReqBody, ReqQuery> { }
Intenta usar esos tipos:
import express from 'express';
const handleMyRequest = (req: express.Request, res: express.Response) => {
// Whatever
}
Respuesta #2
Usé express.Request y express.Response para resolver este problema
import { IUserDTO } from "../entities/User";
import { RegisterUserUseCases } from "./registerUserUseCases"
import express from 'express'
class RegisterUserController {
constructor(private useCase:RegisterUserUseCases){}
async handle(req: express.Request,res: express.Response):Promise<express.Response> {
const { email, name, password, phone } : IUserDTO | any = req.body;
await this.useCase.execute({
email,
name,
password,
phone
})
return res.status(201).json({ message: 'Registo criado com sucesso' })
}
}
export { RegisterUserController }
