我是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
}
您从中间件文件导出的设置不正确。
您正在构造一个具有一个属性isLoggedIn
的对象,该属性是处理程序函数,然后将该对象导出为默认导出。
因此,当您从以下行中的文件导入默认导出时:
import isLoggedIn from '@middleware/user';
现在isLoggedIn
等于默认导出的值。即CCD_ 3是具有一个属性CCD_。因此,您不是像预期的那样将函数传递给route('/').get(...)
,而是将对象传递给它。
您可以使用中间件文件的命名导出:
export const isLoggedIn = (...) => ...;
然后按名称导入:
import {isLoggedIn} from '@middleware/user';
您可以使用as any
类型断言来关闭get参数的类型检查。https://bobbyhadz.com/blog/typescript-no-overload-matches-this-call
lessonRoutes.route('/')
.get(isLoggedIn as any, lessons.lessonForm)