I'm rewriting the backend of an ExpressJS application into Typescript. In auth.routes.ts, I encountered an error related to middleware(authMiddleware). As I understand it, there is a typing error, because the same file in the js extension works fine.
Please help me figure this out.
Below is the corresponding code
auth.routes.ts
import { Router } from "express"
import authMiddleware from "../middleware/auth.middleware"
import authController from "../controllers/authController"
const router = Router()
router.get("/", authMiddleware, authController.auth)
export default router
auth.middleware.ts
import "dotenv/config"
import { NextFunction, Response } from "express"
import jwt, { JwtPayload, Secret } from "jsonwebtoken"
import { CustomHeaders } from "../models"
const secretKey: Secret = process.env.secretKey as Secret
interface AuthRequest extends Request {
user?: JwtPayload
}
function authMiddleware(req: AuthRequest, res: Response, next: NextFunction) {
if (req.method === "OPTIONS") {
next()
}
try {
const token = (req.headers as CustomHeaders).authorization?.split(" ")[1]
if (!token) {
return res.status(401).json({ message: "Unauthorized" })
}
const decoded: JwtPayload = jwt.verify(token!, secretKey) as JwtPayload
req.user = decoded
next()
} catch (error) {
return res.status(400).json({ message: "Bad Request" })
}
}
export default authMiddleware
Error description:
No overload matches this call. The last overload gave the following error. Argument of type '(req: AuthRequest, res: Response<any, Record<string, any>>, next: NextFunction) => Response<any, Record<string, any>> | undefined' is not assignable to parameter of type 'RequestHandlerParams<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'. Type '(req: AuthRequest, res: Response<any, Record<string, any>>, next: NextFunction) => Response<any, Record<string, any>> | undefined' is not assignable to type 'RequestHandler<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'. Types of parameters 'req' and 'req' are incompatible. Type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>' is missing the following properties from type 'AuthRequest': cache, credentials, destination, integrity, and 13 more.ts(2769)
I tried to ask chatGPT about my problem, but I also received non-working variationss