【发布时间】:2021-12-23 14:46:25
【问题描述】:
我在尝试访问我知道存在的对象时遇到错误。
当尝试访问从 AWS Cognito 返回的 event.authorizer 对象的 iam 属性时,一旦我运行它,VS Code 和终端中都会显示错误。
src/private.ts:9:33 - error TS2339: Property 'iam' does not exist on type '{ jwt: { claims: { [name: string]: string | number | boolean | string[]; }; scopes: string[]; }; }'.ts(2339)
这个错误特别令人费解,因为当我打印“事件”对象时,它显示了它存在的证据。
event.requestContext的输出:
{"statusCode":200,"headers":{"Content-type":"text/json"},"body":"{\"event\":{\"accountId\":\"365416766059\",\"apiId\":\"8ihwuguj40\",\"authorizer\":{\"iam\":{\"accessKey\":\"ASIAVKFE... 1068 more characters"}
这表明有一个对象iam 是authorizer 属性的值。这是它存在的证明。那么为什么 VS Code 有问题呢?
我使用npx sst start 运行代码,它运行代码没有问题,并返回预期的event 对象以及authorizer 和awt 嵌套对象。
lambda 函数的完整代码如下。
import { APIGatewayProxyHandlerV2 } from "aws-lambda"
export const handler: APIGatewayProxyHandlerV2 = async (event) => {
const rand = Math.floor(Math.random() * 10)
const authoriser = event.requestContext.authorizer
const accountId = authoriser?.iam.accountId ?? "" // Problem starts with reference to "iam" here.
return {
statusCode: 200,
headers: {"Content-type": "text/json"},
body: JSON.stringify({ message: `Private random number: ${rand}`, accountId: accountId}),
}
}
我试过了:
- 通过附加问号将
iam设为可选。 - 在语句周围使用 try-catch 块。
【问题讨论】:
-
你能试试
const authoriser = JSON.parse(event.requestContext.authorizer)吗? -
@ElliottFrisch 我试过了,我得到了:
Argument of type '{ jwt: { claims: { [name: string]: string | number | boolean | string[]; }; scopes: string[]; }; } | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'.ts(2345)
标签: javascript typescript amazon-web-services aws-lambda