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

TypeScript新手遇req/res隐式any类型错误,JWT认证API如何修复?

Fixing "Implicit 'any' Type" Errors in Your TypeScript JWT Auth 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 RequestWithToken interface extends the base express.Request to include our custom token property.
  • We used express.NextFunction for the next parameter in the middleware, which is required for TypeScript to recognize it as an Express middleware function.
  • The non-null assertion (!) on req.token is safe here because the verifyToken middleware only calls next() if the token exists—so we know it's present when the route handler runs.

内容的提问来源于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 07:59:11