How to write lambdas in Typescript with AWS Amplify

2 minute read

We love Typescript. We love Amplify. In the past it’s been a nuisance to create lambda functions written in Typescript because they must be compiled to javascript before they can be run.

To easily setup your Amplify project so that you can write lambda functions in typescript, follow the steps below.

Setting up your function

Setup your amplify project as usual by running amplify init and following the steps in the CLI. After that, create your first function:

amplify add function

The CLI will ask you a couple of questions to guide you through creating your function:

Once your function is created, duplicate the generated javascript files from amplify/backend/{functionName}/src and rename them as .ts files, within the same folder. You can now start coding your lambda function in typescript! 

Compiling your function

Create a tsconfig.json file in your function’s newly created src folder:

Running tsc in this folder will now compile any .ts files into .js, preserving your folder structure.

To compile the function automatically before pushing it to your stack, add the following line to your project root package.json:

Now, whenever you run amplify push, this script will run beforehand and compile any of your .ts files before it builds your function.

Finally, if you want to hide the generated javascript files from view in VSCode, create a .vscode/settings.json file from your project root and add the following:

This hides .js files within your lambda functions. For debugging, you can always comment this out - but it’s nice to not see double everything whilst developing.