You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript JWT鉴权API遇req/res隐式any类型错误求修复

Fixing "Implicit 'any' Type" Errors for req/res in TypeScript + JWT API

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.Request
  • res → express.Response
  • next → 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 global block extends Express's Request interface to let TypeScript know about the token property we're adding.
  • We use the non-null assertion (!) on req.token! because our verifyToken middleware guarantees that req.token exists by the time the /api/posts handler 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:02:13