Validate the input of your serverless function with 1 line of code

November 07, 2020

simple runtime check

typescript-is is a library which enables type checks at run-time! This is an incredible tool to validate input and make your code more type-safe ๐ŸŽ‰.

Validating the input of cloud functions can be a challenging problem. Re-using your types to ensure that your input matches your type solves a big part of the validation problem. To do this with the typescript-is library, the only thing you need to do is to use the assertType method that typescript-is exports:

// 2. Use the `assertType` method to perform your runtime check
assertType<MyEvent>(input)

Above we use assertType to check whether our runtime object input matches our type MyEvent. If it doesnโ€™t match the MyEvent type, an error is thrown. typescript-is has a bunch of other methods such as is or strictEqual. If youโ€™d like to throw the error yourself you could do this for example:

if (!is<MyEvent>(input)) {
  throw new Error('input does not match type')
}

Thatโ€™s pretty much all it takes to add a run-time type check of your cloud functions input (provided you are a typescript user ๐Ÿ™ƒ). Whereas previously you might have reached for validation libraries such as joi or god-forbid, written your own validator, itโ€™s now just one line of code. What are you going to do with all this new-found time?

Below is the entirety of an AWS lambda function handler with this pattern applied:

import { Handler } from 'aws-lambda'
import { assertType } from 'typescript-is';

type MyEvent = {
  msg: string
}

async function handler<Handler>(event: MyEvent) {
  assertType<MyEvent>(event)
  return { msg: 'Hello World' }
}

exports.handler = handler

๐Ÿš€

For a fully working example of this pattern including deployment scripts for AWS and compilation with webpack please have a look at this boilerplate Iโ€™ve put together.


๐Ÿ™ Thanks for reading

I help software teams build text based editing interfaces