Node AWS SDK v3: Types for `event` and `context` arguments in Lambda functions?
Asked Answered
V

1

12

I'm switching to the new Node AWS SDK (v3) to take advantage of its modularity and Typescript support. The first thing I needed to do was to write a Lambda function, but I can't find types to support the handler function signature. The types in the @aws/client-lambda seem to all be related to, well, a client for managing Lambda.

Does the Node SDK have official types for writing Lambdas somewhere? In particular:

  • Where is the type for the context argument?
  • For event argument, is there a list somewhere of the events that can come from other AWS services and their corresponding types?
interface Event {
  // This could be anything -- a custom structure or something 
  // created by another AWS service, so it makes sense that
  // there isn't a discoverable type for this. There should be
  // corresponding types for each service that can send events
  // to Lambda functions though. Where are these?
}

interface Context {
  // This is provided by Lambda, but I can't find types for it anywhere.
  // Since it's always the same, there should be a type defined somewhere,
  // but where?
}

exports.handler = ( event: Event, context: Context )=>{
  // While `event` could anything so it makes sense to not have a single type available,
  // `context` is always the same thing and should have a type somewhere.
}
Vincenzovincible answered 8/4, 2021 at 13:14 Comment(0)
S
13

Use aws-lambda types, it have types for most of the events.

Example handlers:

import { SQSHandler, SNSHandler, APIGatewayProxyHandler } from 'aws-lambda';

export const sqsHandler: SQSHandler = async (event, context) => {
  
}

export const snsHandler: SNSHandler = async (event, context) => {
}

export const apiV2Handler: APIGatewayProxyHandler = async (event, context) => {
  return {
    body: 'Response body',
    statusCode: 200
  }
}
Serrulation answered 9/4, 2021 at 5:9 Comment(5)
Does this answer imply that the new v3 aws-sdk does not actually provide these types and that the correct solution is to rely on this independent library?Shalne
@types/aws-lambda is pretty much active so I guess this is still the way to go in 2022.Claraclarabella
Yes, event the official docs mention to install this library: docs.aws.amazon.com/lambda/latest/dg/typescript-handler.htmlSiftings
this is correct -- for other scenarios, event can be defined as string | Buffer | any to cover the supported scenarios -- or could be a custom type/interface/class to handle specific objectsDiocesan
...but it would be nice if they offered something like LambdaEvent<T> where T could be the specific contentDiocesan

© 2022 - 2025 — McMap. All rights reserved.