Typescript 没有重载与此调用匹配

问题描述 投票:0回答:1

我是 TypeScript 新手,目前陷入困境。我有一个 next.js 和 Express 应用程序。

我收到以下错误:没有与此调用匹配的重载。

No overload matches this call.
  The last overload gave the following error.
    Argument of type '(req: Request, res: Response, next: NextFunction) => Promise<Response<any, Record<string, any>> | undefined>' is not assignable to parameter of type 'RequestHandlerParams<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.
      Type '(req: Request, res: Response, next: NextFunction) => Promise<Response<any, Record<string, any>> | undefined>' is not assignable to type 'RequestHandler<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.
        Type 'Promise<Response<any, Record<string, any>> | undefined>' is not assignable to type 'void | Promise<void>'.
          Type 'Promise<Response<any, Record<string, any>> | undefined>' is not assignable to type 'Promise<void>'.
            Type 'Response<any, Record<string, any>> | undefined' is not assignable to type 'void'.
              Type 'Response<any, Record<string, any>>' is not assignable to type 'void'.ts(2769)
index.d.ts(203, 5): The last overload is declared here.

我的路线文件是

import { isAuthenticated } from "../middlewares/isAuthenticated";
const router = express.Router();
router.route("/check-auth").get(isAuthenticated, checkAuth);
export default router;

中间件文件是

import { NextFunction, Request, Response } from "express";

declare global {
    namespace Express{
        interface Request {
            id: string;
        }
    }
}

export const isAuthenticated = async (req: Request, res: Response, next: NextFunction) => 
    {
    try {
        const token = req.cookies.token;
        if (!token) {
            return res.status(401).json({
                success: false,
                message: "User not authenticated"
            });
        }
      
        req.id = decode.userId;
        next();
    } catch (error) {
        return res.status(500).json({
            message: "Internal server error"
        })
    }
}
typescript express authentication middleware next.js14
1个回答
0
投票

发生 TypeScript 错误是因为 Express 期望中间件函数返回

void
Promise<void>

通过使函数异步,它会自动返回

Promise
,并且由于您返回
res.status(...).json(...)
(其类型为
Response
),因此该函数的返回类型与 Express 预期的
Promise<void>
不一致。

在 Express 中,中间件函数 应该调用 next() 或结束响应而不返回任何值。 删除异步或确保所有路径返回 Promise

已更新 isAuthenticated.ts

export const isAuthenticated = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
        const token = req.cookies?.token;
        if (!token) {
            res.status(401).json({ success: false, message: "User not authenticated" });
            return; // Exit without returning a Response
        }
        req.id = "exampleUserId"; // Assume this ID is decoded from token
        next();
    } catch (error) {
        res.status(500).json({ message: "Internal server error" });
    }
};
© www.soinside.com 2019 - 2024. All rights reserved.