Interesting Finds: io-ts Runtime Type Checker
June 01 2017
Some situations need extra caution, though. For instance, there is no way for a compiler to type check the types of I/O operations. The Typescript compiler has no control over the outside world- this includes things like AJAX, Websockets and file operations.
One way to bring safety to a project’s I/O operations is to write user defined type guards.
It’s a great way to handle unknown runtime types, but it can create excess boilerplate and conditional logic as well.
One library I recently discovered to tackle the issue of runtime type checking is io-ts. Although I haven’t used it in any major projects yet, it does look like a promising way to add type safety to unsafe runtime operations. It uses type guards under the hood, but comes with many conveniences to keep code DRY.
The documentation does a good job of explaining how it works.
Here’s an example that downloads JSON data over AJAX (via the Axios AJAX library):
Looking at it in an editor, we can see that Typescript has no problem inferring the type:
Io-ts looks like a promising, actively maintained project. I hope more developers give it a look.
The example above is only scratching the surface. If you are curious to learn more, check them out on NPM or Github.