I have a simple lambda function written in typescript ( little to no experience)
I am trying to extract query string parameters from event object received to lambda but it tells me this error.
(property) APIGatewayProxyEventV2WithRequestContext<APIGatewayEventRequestContextV2>.queryStringParameters?: APIGatewayProxyEventQueryStringParameters | undefined
'event.queryStringParameters' is possibly 'undefined'.ts(18048)
Here is my lambda code
import { APIGatewayProxyEventV2, APIGatewayProxyResultV2, APIGatewayProxyEventV2WithRequestContext, Context } from 'aws-lambda';
const region = process.env.AWS_REGION
export async function handler(
event: APIGatewayProxyEventV2): Promise<APIGatewayProxyResultV2> {
console.log('event 👉', event);
const token = event.queryStringParameters.token
const Url = event.queryStringParameters.Url
const message = event.Records[0].Sns.Message. //If I get event from aws service similar error.
if (token) {
await sendApproval(event.queryStringParameters)
return {
statusCode: 301,
headers: {
Location: Url,
}
};
} else {
return {
body: JSON.stringify({ message: 'Oops Approval was not sent successfully' }),
statusCode: 502,
};
}
}
IN a similar fashion if there is an event from aws services which required me to extract it. It has a similar kind of error where Records does not exist const message = event.Records[0].Sns.Message
In order to solve this I am fixing it with a !
operator.
const token = event.queryStringParameters!.Token
const Url = event.queryStringParameters!.Url
Is this the only to fix it?
2
Answers
The ‘@types/aws-lambda’ package is trying to warn you that
queryStringParameters
attribute may not exist on the incoming event.By using the
!
, you are telling the TypeScript compiler that the type definition is wrong and that thequeryStringParameters
will never beundefined
.A better way to write the code would be to accept that the
queryStringParameters
may beundefined
and add some code to handle it, avoiding an unexpected, and difficult to diagnose, error.There are a couple ways of handling this
constant token = event.queryStringParameters[‘Token’]