如何在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
相关产品推荐
相关产品推荐

