TECHNOLOGY

Typescript Runtime Validation With io-ts

How you can enforce your data contracts in an easy and elegant way

Sebastian Walther
The Startup
Published in
5 min readSep 6, 2020

--

Photo from pxhere.com

The Problem

Every time our application receives some data input via an application boundary at runtime, it should be at least validated against a data scheme. In typed languages like Typescript, it also makes sense to map the input data to a known type after validation. Examples for such input data would be files uploaded from the file system, REST response bodies or serialized database entries. How can we deal with this task in an efficient, elegant and transparent way?

Alternative Solutions

There are three popular approaches in the domain of runtime typing and validation. They differ mostly regarding the point of time when the validations actually happens and how the user can define the rules.

  • Schema files: this approach defines a data schema in a standardized schema file and validates the input against this schema on runtime. JSON schema is a popular example for this approach (https://json-schema.org/). Advantages are that most schema formats are quite expressive and files can easily be versioned. On the contrary, type definitions must be derived from the schema file at build/ compile time and can…

--

--