Migrating to TypeScript from ES2015 for AWS Lambda

Posted by on Oct 12, 2016 in AWS, Cloud, JavaScript

I was recently building an skill for the Amazon Alexa platform (think Amazon Echo, Fire tablets, Echo Tap etc). Like anyone writing JavaScript today I naturally levitated toward some of the syntactic goodness that ES2015 offers – arrow functions, let variable scoping, string literal templating, default parameters etc all of which make JavaScript a much, much nicer language (and much, much closer to C# incidentally which is where the language seems to be heading long-term looking at current and new functionality. Alas, I digress!).

I had the skill up and running locally (bridged via an Express.js node front end for testing) and everything was working well. Then it came the time to upload my skill to the amazon developer portal and migrate my function to AWS Lambda. This is where the fun started – it turns out Lambda uses a fairly dated version of Node.js that doesn’t support much of the ES2015 specification.
This left me faced with two options – strip out all the ES2015 code and rewrite using vanilla JavaScript or make use of our friend, Typescript. To be honest I should have gone down the TypeScript route from the offset; in hindsight I’m not sure why anyone would write straight JavaScript nowadays when the TypeScript transpiler does such a great job of both supporting new functionality and also outputting compliant ES5 code.
The task of migrating from JavaScript was as easy as 1-2-3:

  1. Rename all my .js files to .ts
  2. Install tsc from the command line (npm install –g tsc) and create my tsconfig.json with the list of files in my project
  3. Run typescript in watch mode (tsc –w) to get it to watch for changes to save (my lazy hands) having to recompile manually

Once this was done I was free to do nothing more and I already had fully “Lambda compliant” JavaScript that I could use. However, the TypeScript compiler can do so much more for me, so I spent a little time going through my code adding in types to all my parameters, created an object interface so TS knew the type of data I was passing around on properties on the object (this also greatly improved Intellisense in VS Code I might add) and pulled down some typings for the third party libraries I was using.

Migration was such a smooth and painless experience and I’m now in a much better place than I was prior to the conversion. I have compile time type checking, I get to use the much more elegant and succinct ES2015 syntax and I have a much better development environment through the “knowledge” TypeScript now has about my code.