CodeSOD: Literal Type Checking

This post was originally published on this site

The Daily WTF

Validating your inputs is important, even when the sender is an API- in the land of JSON-based data exchange, we can’t guarantee which keys exist without checking.

Philipp‘s team uses the “Runtypes” library to solve this problem. It lets them write code like this:

r.Array(r.Record({ id: r.Number, name: r.String })).check(inputData)

This verifies that inputData is an array of objects with id fields (containing numbers), and a name field (containing strings).

For more complex validation, Runtypes lets you use add constraint functions to your types. So, for example, if you wanted to ensure a number is in the range of 0-52, you could do:

const YearIndexes = r.Number.withConstraint((n) => n >= 0 && n <= 52);

You could do that. But Phillip’s co-worker wanted to find a more declarative approach that doesn’t have any of those pesky function calls in it.

const YearIndexes = Union( Literal(‘0’), Literal(‘1’), Literal(‘2’), Literal(‘3’),

To read the full article click on the 'post' link at the top.