writing aws lambdas in typescript using sam

2020-10-29

 | 

~2 min read

 | 

344 words

I recently discovered AWS’s SAM cli for managing serverless applications.

On the face, this feels like a fantastic way to manage new applications that can benefit from a serverless architecture.

There’s just one hiccup: I like working with Typescript more than vanilla Javascript at this point. Fortunately Zijing Zhao beat me to the punch and wrote an article on how to use Typescript with AWS Lambda’s (in fact, her article was my introduction to sam in the first place!).

So, what are the steps?

  1. Add dependencies
  2. Initialize typescript
  3. Refactor

Add Dependencies

At a minimum, we need three dependencies:

$ yarn add --dev @types/aws-lambda @types/node typescript

Initialize Typescript

As I wrote about in my previous post on setting up Typescript for a new project we can get started quickly with:

$ ./node_modules/.bin/tsc --init

Zijing’s recommended settings are:

tsconfig.json
{
  "compilerOptions": {
    "module": "CommonJS",
    "target": "ES2017",
    "noImplicitAny": true,
    "preserveConstEnums": true,
    "outDir": "./built",
    "sourceMap": true
  },
  "include": ["src-ts/**/*"],
  "exclude": ["node_modules", "**/*.spec.ts"]
}

Refactor

There are a few things that we now have to refactor:

  1. The app.js becomes app.ts (with types!)
  2. Update the template.yml to reflect the new destination for where our app will live (i.e. our outDir)

Again, Zijing provided a nice example that included the types:

app.ts
import { APIGatewayProxyEvent, APIGatewayProxyResult } from "aws-lambda"

export const lambdaHandler = async (
  event: APIGatewayProxyEvent,
): Promise<APIGatewayProxyResult> => {
  const queries = JSON.stringify(event.queryStringParameters)
  return {
    statusCode: 200,
    body: `Queries: ${queries}`,
  }
}

This lambda doesn’t do anything except receive an event from the API Gateway and return a 200 with the queries in the body of the response, but we can see how the event and response would be typed.

I am confident that as I get into building more complicated applications, I’ll find holes in my understanding, but I’m grateful to Zijing for the first pass! She saved me a ton of time, introduced me to a new AWS tool, and inspired me to go looking for more information to fill in the gaps!


Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!