Add types to your AWS lambda handler

Lambdas handlers can be invoked with many different, but always complex, event arguments. Add to that the context, callback, matching return type and you basically start listing all the different ways that your function can fail in production.

Watch me here to work through this example or keep reading:

In the wild I see most people either NOT add types around their lambda handlers, and try to figure out what's available to them searching through the documentation, or add the types manually, the way they THINK they should be.

Luckily there is much better way.

Add @types/aws-lambda package as your devDependency.

Then you can import types from that package and use it:

import type { APIGatewayProxyHandlerV2 } from "aws-lambda";  
  
export const handler: APIGatewayProxyHandlerV2 = async (event, context, info) => {  
  const {queryStringParameters} = event;
}

If you have specific data you always return from the function you can specify it with generics:

type ReturnedData = {
  sum: number
}
export const handler: APIGatewayProxyHandlerV2<ReturnedData> = async (event, context, info) => {
  const {queryStringParameters} = event;

  return {
    sum: parseInt(queryStringParameters.a) + parseInt(queryStringParameters.b)
  }
}

What's nice here is that now you can export that type and reuse it in a different place - perhaps you call this lambda function from a different lambda function, now you can have a typed integration.

API Gateway might be the most common used lambda but there @types/aws-lambda package provides you with most (if not all) you could need, handlers for SQS, SNS, dynamodb streams, and so on.

Let me know if you have any questions or thoughts in the comments below.


Let us help you on your journey to Quality Faster

We at Xolv.io specialize in helping our clients get more for less. We can get you to the holy grail of continuous deployment where every commit can go to production — and yes, even for large enterprises.

Feel free to schedule a call or send us a message below to see how we can help.

User icon
Envelope icon

or

Schedule a 30m call
  • How to expose a local service to the internet

    From time to time you might need to expose your locally running service to the external world - for example you might want to test a webhook that calls your service. To speed up the test/development feedback loop it would be great to be able to point that webhook to your local machine.

  • For loops in JavaScript (vs _.times)

    From time to time I still see a for loop in JavaScript codebases. Linters are frequently angry about them. Let's see how we can replace them.

  • Sharing scalars between modules with Chimp

    Simplify your Chimp-based project even further with a new @predefined Scalar directive.