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

JS后端项目转TS时Webstorm无错误提示,求verifyToken代码改造示例

解决Webstorm无错误提示问题

你当前的tsconfig未开启严格类型校验规则,是没有错误提示的核心原因,按以下步骤调整即可:

  • 安装依赖类型声明包:执行 npm install @types/node @types/express @types/jsonwebtoken -D 安装后端相关的类型定义。
  • 修改tsconfig.json,开启严格校验,调整后配置如下:
{
  "compilerOptions": {
    "esModuleInterop": true,
    "target": "ES2020",
    "moduleResolution": "node",
    "module": "CommonJS",
    "strict": true,
    "skipLibCheck": true,
    "outDir": "./dist"
  }
}

修改完成后右键项目中的tsconfig.json文件,选择「Apply TypeScript Compiler Options to Project」,让Webstorm加载新的TS配置。


verifyToken中间件TS改造代码

因为需要在Express的Request对象上挂载自定义的userId属性,需要先扩展Request的类型定义,改造后的完整代码如下:

import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';
// 注意替换为你实际的config文件导入路径
import config from './config';

// 扩展Express Request类型,新增userId字段
declare module 'express-serve-static-core' {
  interface Request {
    userId?: string | number; // 根据你实际的id类型调整即可
  }
}

const verifyToken = (req: Request, res: Response, next: NextFunction) => {
  const token = req.headers["authorization"];

  if (!token) {
    return res.status(403).send({
      message: "No token provided"
    });
  }

  jwt.verify(token, config.secret, (err, decoded) => {
    if (err) {
      return res.status(401).send({
        message: "Unauthorized"
      });
    }
    // 类型守卫避免decoded为空报错
    if (decoded && typeof decoded === 'object' && 'id' in decoded) {
      req.userId = decoded.id;
    }
    next();
  });
};

export default verifyToken;

如果后续还有多个文件需要用到扩展后的Request类型,可以把上面的类型声明单独放到项目根目录的typings/express/index.d.ts文件中,无需每个文件重复声明。

内容的提问来源于stack exchange,提问作者Steve Halla

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 02:36:03