TypeScript新手遇req/res隐式any类型错误,JWT认证API如何修复?
Hey there! Let's sort out that TypeScript error you're hitting. The "Parameter 'req' implicitly has an 'any' type" warnings pop up because TypeScript can't infer the types of the req (request) and res (response) objects in your Express routes and middleware. Since TypeScript is strict about type safety, it flags these implicit any types as issues. Here's how to fix it step by step:
Step 1: Install Express Type Definitions
First, make sure you have the official TypeScript type definitions for Express installed. These definitions tell TypeScript what properties and methods are available on req and res:
npm install @types/express --save-dev
Step 2: Add Explicit Types to Route Handlers
Update your route functions to explicitly type req as express.Request and res as express.Response. This gives TypeScript the context it needs to validate your code.
Step 3: Extend the Request Type for Your Custom Token Property
Your verifyToken middleware adds a token property to the req object, which isn't part of the default Express Request type. We'll create a custom interface to extend the base Request type and include this property.
Updated Full Code
Here's your revised code with all type fixes applied:
import express from 'express'; import jwt from 'jsonwebtoken'; const app = express(); // Don't forget this middleware to parse JSON request bodies app.use(express.json()); // Custom interface to extend Express Request with our token property interface RequestWithToken extends express.Request { token?: string; } app.get('/api', (req: express.Request, res: express.Response) => { res.json({ message: 'Welcome to the API' }); }); app.post('/api/posts', verifyToken, (req: RequestWithToken, res: express.Response) => { // We use the non-null assertion (!) here because verifyToken ensures token exists before calling next() jwt.verify(req.token!, 'secretkey', (err, authData) => { if (err) { res.sendStatus(403); } else { res.json({ message: 'Post created...', authData }); } }); }); app.post('/api/login', (req: express.Request, res: express.Response) => { // Mock user const user = { id: 1, username: 'brad', email: 'brad@gmail.com' }; jwt.sign({ user }, 'secretkey', (err, token) => { res.json({ token }); }); }); function verifyToken(req: RequestWithToken, res: express.Response, next: express.NextFunction) { const bearerHeader = req.headers['authorization']; if (typeof bearerHeader !== 'undefined') { const bearer = bearerHeader.split(' '); const bearerToken = bearer[1]; req.token = bearerToken; next(); } else { res.sendStatus(403); } } // Start your server (add your port number) app.listen(3000, () => { console.log('Server running on port 3000'); });
Key Notes:
- We added
app.use(express.json())to parse JSON request bodies (you'll need this for the login route to work correctly). - The
RequestWithTokeninterface extends the baseexpress.Requestto include our customtokenproperty. - We used
express.NextFunctionfor thenextparameter in the middleware, which is required for TypeScript to recognize it as an Express middleware function. - The non-null assertion (
!) onreq.tokenis safe here because theverifyTokenmiddleware only callsnext()if the token exists—so we know it's present when the route handler runs.
内容的提问来源于stack exchange,提问作者Mozart Len

