skip to Main Content

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


  1. 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 the queryStringParameters will never be undefined.

    A better way to write the code would be to accept that the queryStringParameters may be undefined and add some code to handle it, avoiding an unexpected, and difficult to diagnose, error.

    const token = event.queryStringParameters?.token
    if (!token) {
        throw new Error("The token query string parameter was not found on the request!");
    }
    
    Login or Signup to reply.
  2. There are a couple ways of handling this

    1. You can check if event.queryStringParameters is defined before attempting to access the field.
    2. You can use the object index accessor like constant token = event.queryStringParameters[‘Token’]
    3. You can disable strict mode in your tsconfig (not recommended)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search