我是 TypeScript 新手,目前陷入困境。我有一个 Nodejs 和 Express 应用程序。
我收到以下错误:没有与此调用匹配的重载。
The last overload gave the following error.
Argument of type '{ isLoggedIn: (req: Request<ParamsDictionary, any, any, QueryString.ParsedQs, Record<string, any>>, res: Response<any, Record<string, any>>, next: NextFunction) => Response<...> | undefined; }' is not assignable to parameter of type 'RequestHandlerParams<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.
Type '{ isLoggedIn: (req: Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>, res: Response<any, Record<string, any>>, next: NextFunction) => Response<...> | undefined; }' is missing the following properties from type '(ErrorRequestHandler<ParamsDictionary, any, any, ParsedQs, Record<string, any>> | RequestHandler<ParamsDictionary, any, any, ParsedQs, Record<...>>)[]': length, pop,
export {}
import express, { Router } from 'express';
import lessons from '@controllers/lessons';
import isLoggedIn from '@middleware/user';
const lessonRoutes: Router = express.Router();
lessonRoutes.route('/')
.get(isLoggedIn, lessons.lessonForm)
这是我的中间件文件
import { Request, Response, NextFunction } from 'express';
const isLoggedIn = (req: Request, res: Response, next: NextFunction) => {
if (!req.isAuthenticated()) {
return res.status(401).json({
error: "User must sign in"
})
}
next();
}
export default {
isLoggedIn
}
您可以使用
as any
类型断言来关闭对 get 参数的类型检查。
https://bobbyhadz.com/blog/typescript-no-overload-matches-this-call
lessonRoutes.route('/')
.get(isLoggedIn as any, lessons.lessonForm)
您从中间件文件的导出设置不正确。
您正在构造一个具有一个属性
isLoggedIn
(即处理函数)的对象,然后将该对象导出为默认导出。
因此,当您从该文件中导入默认导出时:
import isLoggedIn from '@middleware/user';
现在
isLoggedIn
等于默认导出的值。即 isLoggedIn
是一个具有一个属性 isLoggedIn
的对象,该属性等于处理函数。因此,您不是像预期那样将函数传递给 route('/').get(...)
,而是向它传递一个对象。
您可以使用中间件文件中的命名导出来代替:
export const isLoggedIn = (...) => ...;
然后按名称导入:
import {isLoggedIn} from '@middleware/user';
记得使用:Promise
从 'express' 导入 { Request, Response, NextFunction };
const isLoggedIn = (req: 请求, res: 响应, next: NextFunction):Promise=> { if (!req.isAuthenticated()) { 返回 res.status(401).json({ 错误:“用户必须登录” }) } 下一个(); }
导出默认值{ 已登录 }
这将解决新更新后的打字稿问题