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

Express中Request泛型Locals类型的作用是什么?

Express Request泛型Locals的用途及req.auth扩展问题解析

你尝试通过Request的第五个泛型参数(Locals)定义req.auth属性却报错,核心原因是这个泛型并非用来扩展Request的顶层属性,而是专门约束req.locals对象的类型。

为什么你的代码报错?

Express的Request类型中,顶层属性(如req.auth)不属于Locals泛型的管辖范围。Locals泛型的作用是规范req.locals——这是Express官方预留的、用于中间件间传递自定义临时数据的容器,而非给req添加顶层属性的工具。

正确扩展req顶层属性的方式

若要给Request添加顶层的auth属性,需通过模块类型扩展修改Express的类型定义:

  1. 在项目中创建类型定义文件(比如types/express.d.ts),写入以下内容:
declare namespace Express {
  interface Request {
    auth: {
      token: string;
      payload: object;
    };
  }
}
  1. 在tsconfig.json中确保该类型文件被识别:
{
  "compilerOptions": {
    "typeRoots": ["./node_modules/@types", "./types"]
  }
}

Locals泛型的实际用法

当你需要在中间件间通过req.locals传递数据时,用这个泛型约束其类型,能获得精准的类型提示:

import { Request, Response, NextFunction } from "express";

interface RequestLocals {
  auth: {
    token: string;
    payload: object;
  };
}

// 赋值中间件
const authMiddleware = (req: Request<{}, {}, {}, {}, RequestLocals>, res: Response, next: NextFunction) => {
  req.locals.auth = {
    token: "sample-token",
    payload: { userId: 1001 }
  };
  next();
};

// 使用数据的中间件
const exampleMiddleware = (req: Request<{}, {}, {}, {}, RequestLocals>, res: Response) => {
  console.log(req.locals.auth.token); // 有正确的类型提示
  res.send("处理完成");
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 03:33:16