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

如何在NestJS中为请求的Session User声明全局类型及返回类型?

在NestJS中为Express Request的User接口全局定义类型

1. 创建全局类型声明文件

在项目的src/types目录下新建express.d.ts文件,扩展Express内置的User接口,添加业务所需的用户字段:

// src/types/express.d.ts
declare global {
  namespace Express {
    interface User {
      id: string;
      username: string;
      email: string;
      // 根据需求添加其他字段,比如role、createdAt等
    }
  }
}

// 导出空对象确保文件被TypeScript识别为模块
export {};

2. 配置TypeScript识别类型文件

打开项目根目录的tsconfig.json,确保include数组包含你的类型文件路径,让TypeScript编译时加载全局类型:

{
  "compilerOptions": {
    // 保留原有编译配置
  },
  "include": ["src/**/*", "src/types/**/*.d.ts"]
}

3. 在控制器中使用带类型的User

此时request.user会自动拥有你定义的类型,同时可明确指定接口的返回类型:

import { Controller, Get, Req } from '@nestjs/common';
import { Request } from 'express';

@Controller('auth')
export class AuthController {
  @Get('authenticated')
  async authenticated(@Req() request: Request): Promise<Express.User> {
    const user = request.user;
    return user;
  }
}

关键说明

  • 若使用Fastify作为NestJS的HTTP适配器,只需将namespace Express替换为namespace Fastify,并对应修改Request的导入来源
  • 类型文件的.d.ts后缀是必须的,导出空对象是为了避免全局作用域冲突,让TypeScript将其视为模块文件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 15:43:13