express - Typescript 沒有符合此呼叫的重載
我剛開始接觸 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"
})
}
}
答案#1
TypeScript 錯誤發生的原因是 Express 預期中介軟體函數應返回 void 或 Promise<void>。
透過將你的函式設為 async,它會自動回傳一個 Promise,而因為你回傳的是 res.status(...).json(...)(它的型別是 Response),所以函式的回傳型別與 Express 預期的 Promise<void> 不一致。
在 Express 中,中介軟體函數應該要么呼叫 next(),要么結束回應而不返回任何值。要么移除 async,要么確保所有路徑都返回 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" });
}
};
