TypeScript JWT鉴权API遇req/res隐式any类型错误求修复
Hey there! Those errors you're seeing—Parameter 'req' implicitly has an 'any' type and Parameter 'res' implicitly has an 'any' type—are coming from TypeScript's strict type-checking rules. TypeScript requires every variable (including function parameters like req and res) to have a clear type declaration, and right now yours are being inferred as any (which is blocked in strict mode). Let's fix this step by step:
1. First, install Express type definitions
TypeScript doesn't know about Express's request/response types out of the box, so we need to install the official type package:
npm install @types/express --save-dev
2. Add explicit types to your request handlers and middleware
We'll use Express's built-in types for req, res, and next:
req→express.Requestres→express.Responsenext→express.NextFunction
Also, since you're adding a custom token property to req in your verifyToken middleware, we need to extend Express's Request interface so TypeScript recognizes this new property.
Here's your updated code with all fixes applied:
import express from 'express'; import jwt from 'jsonwebtoken'; const app = express(); // Don't forget this line—it lets Express parse JSON request bodies app.use(express.json()); // Extend Express's Request interface to include our custom token property declare global { namespace Express { interface 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: express.Request, res: express.Response) => { // We use ! here because verifyToken ensures req.token exists before reaching this handler 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: express.Request, 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); } } // Example server startup (add this if you don't have it already) app.listen(3000, () => { console.log('Server running on port 3000'); });
Quick notes about the changes:
- The
declare globalblock extends Express'sRequestinterface to let TypeScript know about thetokenproperty we're adding. - We use the non-null assertion (
!) onreq.token!because ourverifyTokenmiddleware guarantees thatreq.tokenexists by the time the/api/postshandler runs (if it didn't, we would've already sent a 403 response and stopped execution). - I added
app.use(express.json())—this is essential for parsing JSON request bodies, which you'll need if you ever move beyond mock users in your login route.
After making these changes, your npm start should run without those implicit any errors!
内容的提问来源于stack exchange,提问作者Mozart Len

