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

如何扩展TypeScript模块且不覆盖?Fastify会话类型扩展遇错

解决Fastify扩展Session类型时的导入错误

问题根源

你遇到的两种写法都存在模块类型覆盖的问题:

  • 第一种写法未添加任何import/export语句,TypeScript将其判定为全局声明文件,直接覆盖了fastify模块的原有类型定义,导致Fastify的调用签名和其他导出类型全部丢失。
  • 第二种写法通过export = Fastify重新定义了整个fastify模块,仅保留默认导出的Fastify构造函数,原模块的其他导出类型(如FastifyRequest)被覆盖,自然无法找到。

正确的扩展方式

情况1:扩展@fastify/session插件的Session类型

如果你使用@fastify/session插件实现会话功能,需要扩展该插件提供的Session接口,而非Fastify核心模块:

// 在项目的类型声明文件中(比如 src/types/fastify-session.d.ts)
import '@fastify/session';

declare module '@fastify/session' {
  interface Session {
    user_id: string;
    other_key: your_prefer_type; // 替换为你的实际类型
    id?: number;
  }
}

情况2:给FastifyRequest添加自定义会话属性

如果是自行实现会话逻辑,需要扩展FastifyRequest接口,添加自定义的session属性:

// 在项目的类型声明文件中(比如 src/types/fastify.d.ts)
import 'fastify';

declare module 'fastify' {
  interface FastifyRequest {
    session: {
      user_id: string;
      other_key: your_prefer_type;
      id?: number;
    };
  }
}

额外配置

确保你的tsconfig.json包含自定义类型文件路径:

{
  "compilerOptions": {
    "typeRoots": ["./node_modules/@types", "./src/types"]
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 09:39:22