Everyone knows that validating user input is the cornerstone of all web programming. In fact, all data coming into (and perhaps data that is leaving l

Parse, don’t validate, incoming data in TypeScript.

submited by
Style Pass
2021-09-05 17:00:12

Everyone knows that validating user input is the cornerstone of all web programming. In fact, all data coming into (and perhaps data that is leaving leaving) your software should be validated. So what’s this mockery of parsing it instead? What’s this parse, don’t validate (you might want to read that sometime later) mumbo jumbo?

Let’s grab a popular JavaScript validation library like yup. Note that we might as well use other popular libraries like joi or a JSON validator like ajv instead, the point we are making would still stay the same.

The above code does a good job of validating data and ensuring it’s valid according to our schema. We have a good chance of creating a precise schema and there’s good support for custom validation logic. It’s quite maintainable too, easy to reuse, extend and so forth. So what’s the problem?

In lines 24–27 we can easily handle the pass/fail cases and continue with our business logic if the data instead is valid (and perhaps return a 400 error or similar if it’s not). However, we still don’t have a type for our data. It’s still any/unkown. Sure, we can typecast it but that poses a problem: we now have to maintain a schema and a type separately, by hand, and nothing is really making sure they match.

Leave a Comment