Cho*_*wka 7 node.js express typescript
我正在尝试使用 TypeScript 在 Express 中创建一条路由,因此我像往常一样,将函数的参数设置createUser
为req
: Request
、res
:Response
和next
: NextFunction
, from @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.
Run Code Online (Sandbox Code Playgroud)
如何解决这个问题?这是该应用程序的一些代码:
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,
});
}
}
Run Code Online (Sandbox Code Playgroud)
Pyt*_*tth 12
我很惊讶这对你竟然有效。Express 有自己的类型可用于请求和响应,扩展了您正在使用的基本类型。
例如,以下是快速请求的类型定义:
interface Request<P = core.ParamsDictionary, ResBody = any, ReqBody = any, ReqQuery = core.Query> extends core.Request<P, ResBody, ReqBody, ReqQuery> { }
Run Code Online (Sandbox Code Playgroud)
尝试使用这些类型:
import express from 'express';
const handleMyRequest = (req: express.Request, res: express.Response) => {
// Whatever
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10017 次 |
最近记录: |