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

TypeScript重写Express Request的User接口出现类型错误如何解决

Express自定义User类型不生效解决方法

调整声明文件格式

根据你的声明文件是否有导入其他内容,选择对应的写法:

  • 无其他导入/导出的声明文件,直接删除declare global包裹,示例代码:
namespace Express {
  export interface Request {
    user?: User;
  }

  interface User {
    name: string;
    token: string
  }
}
  • 有导入其他类型的声明文件,保留declare global块,示例代码:
import type { CustomType } from './your/types/path';

declare global {
  namespace Express {
    export interface Request {
      user?: User;
    }

    interface User {
      name: string;
      token: string;
      customField?: CustomType;
    }
  }
}

注意声明文件后缀必须为.d.ts,建议命名为express.d.ts,存放在项目根目录的@types文件夹下。

修正tsconfig配置

不需要额外调整typesRoot也可以生效,只需要确保声明文件在TS的包含范围内:

{
  "compilerOptions": {
    // 其他原有配置不变,如果配置了typeRoots需要加入本地类型目录
    "typeRoots": ["./node_modules/@types", "./@types"]
  },
  "include": [
    "src/**/*",
    // 加入声明文件存放路径
    "@types/**/*"
  ]
}

验证生效

  1. 确保已安装官方类型包:npm i @types/express -D,避免版本过低导致类型合并失败
  2. 重启TS语言服务:VSCode用户按Cmd/Ctrl + Shift + P,执行Restart TypeScript Server即可

如果你引入了@types/express-jwt等会自动扩展Express Request类型的依赖,不需要重复声明Request上的user字段,直接扩展User接口即可自动合并类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 13:06:04