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

如何在d.ts中扩展AWS Lambda的APIGatewayProxyEvent类型?

扩展aws-lambda的APIGatewayProxyEvent类型解决方案

问题原因分析

  • 第一种写法使用AWSLambda命名空间:由于aws-lambda的官方类型定义采用模块导出而非命名空间,这种写法相当于重新声明了一个全新的APIGatewayProxyEvent接口,而非扩展原有类型。
  • 第二种写法报错重复标识符:因为你在扩展时重写了原接口已存在的body属性,TypeScript不允许接口合并时覆盖现有属性,因此触发Duplicate identifier错误。

正确实现方式

方式一:仅扩展新属性(推荐)

如果只需要给原接口添加新属性、保留原有属性类型,直接在模块声明中添加新字段即可:

// 示例文件:src/types/aws-lambda.d.ts
import 'aws-lambda';

declare module 'aws-lambda' {
  interface APIGatewayProxyEvent {
    // 仅添加原接口没有的属性
    user: any;
  }
}

方式二:修改原有属性类型(若需调整body类型)

如果必须修改body这类原有属性的类型,无法通过接口合并直接重写,可借助Omit工具类型创建自定义扩展类型:

import { APIGatewayProxyEvent } from 'aws-lambda';

// 移除原body属性,再合并自定义的body和新属性
export type CustomAPIGatewayProxyEvent = Omit<APIGatewayProxyEvent, 'body'> & {
  body: any;
  user: any;
};

之后在业务代码中直接使用CustomAPIGatewayProxyEvent替代原APIGatewayProxyEvent即可。

额外配置检查

确保tsconfig.json包含自定义的d.ts文件,避免类型无法被识别:

{
  "compilerOptions": {
    "target": "ES2022",
    "esModuleInterop": true,
    "moduleResolution": "node",
    "forceConsistentCasingInFileNames": true,
    "isolatedModules": true,
    "baseUrl": "."
  },
  "include": ["./**/*.ts", "./**/*.d.ts"]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 15:24:18