AWS Lambda对接Cognito时iam属性存在却报TS2339不存在错误
问题根因
这是TypeScript编译期类型校验报错,和实际运行时的字段存在性无关:aws-lambda包导出的APIGatewayProxyHandlerV2默认适配API Gateway JWT授权器场景,其内置的authorizer属性类型仅声明了jwt子属性,没有包含IAM授权器对应的iam子属性,因此TypeScript做静态检查时会抛出TS2339错误。你用npx sst start运行正常,是因为类型检查仅在编译阶段生效,运行时实际存在iam字段所以不会触发异常。
你之前尝试的加可选链、包裹try-catch都无效,是因为问题本质是类型定义中根本没有声明iam属性,不是属性可能为空或者运行时异常,这两种操作都无法解决编译期的类型校验问题。
解决方法
方法1:临时类型断言(快速适配)
直接用as关键字告知TypeScript你确认iam属性存在,适合单次使用的场景:
// 最简单的写法,直接断言为any跳过类型检查 const accountId = (authoriser as any)?.iam.accountId ?? ""
如果需要更规范的类型约束,可以自定义IAM授权器的类型:
interface IAMAuthorizer { iam: { accessKey: string; accountId: string; // 按需补充其他iam下的用到的字段 } } // 访问时做类型断言 const accountId = (authoriser as IAMAuthorizer)?.iam.accountId ?? ""
方法2:扩展事件类型(全局复用)
自定义继承原生API Gateway事件类型,替换authorizer的类型定义,适合多个同场景Lambda函数复用的场景:
import { APIGatewayProxyEventV2, APIGatewayProxyHandlerV2 } from "aws-lambda" // 自定义带IAM授权器的事件类型 interface APIGatewayIAMAuthorizerEvent extends APIGatewayProxyEventV2 { requestContext: Omit<APIGatewayProxyEventV2['requestContext'], 'authorizer'> & { authorizer: { iam: { accessKey: string; accountId: string; // 按需补充其他需要的字段 } } } } // 给handler指定自定义的事件类型 export const handler: APIGatewayProxyHandlerV2<APIGatewayIAMAuthorizerEvent> = async (event) => { const rand = Math.floor(Math.random() * 10) const authoriser = event.requestContext.authorizer // 此处直接访问iam不会再报类型错误 const accountId = authoriser?.iam.accountId ?? "" return { statusCode: 200, headers: {"Content-type": "text/json"}, body: JSON.stringify({ message: `Private random number: ${rand}`, accountId: accountId}), } }
内容的提问来源于stack exchange,提问作者Luke Martin
相关产品推荐
相关产品推荐

