gpt4 book ai didi

node.js - Express TypeScript 路由属性

转载 作者:行者123 更新时间:2023-12-04 08:29:08 25 4
gpt4 key购买 nike

我正在尝试使用 TypeScript 在 Express 中创建路由,因此我像往常一样设置了 createUser 的参数。函数到 req :Request , res :Responsenext :NextFunction ,来自 @types/express , 明显地。它每次都有效,但这次它显示错误:

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.
如何解决?
这是应用程序的一些代码:
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,
});
}
}

最佳答案

我很惊讶这对你有用。 Express 有自己的类型可用于请求和扩展您正在使用的基本类型的响应。
例如,这里是 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> { }
尝试使用这些类型:
import express from 'express';


const handleMyRequest = (req: express.Request, res: express.Response) => {
// Whatever
}

关于node.js - Express TypeScript 路由属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65112240/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com