3 ms·
I've been looking for a solid Typescript implementation of "parse don't validate" that performs runtime parsing using semantics attached to the defined Typescri
by ledauphin 5y ago
I've been looking for a solid Typescript implementation of "parse don't validate" that performs runtime parsing using semantics attached to the defined Typescript types themselves. In other words, much like attrs for Python, I want to be able to define a low/no-boilerplate type, and then register parsers for those types that will work recursively to parse my data, resulting in the specified Typescript type.
Has anyone seen or written something like this?
- bmuon 5y agoI've been using this small library inspired by Elm/Swift decoders [1]. It works, but it's not low boilerplate. I'm gravitating towards GraphQL now because strict parsing is built into it, so there is no need for all this boilerplate. https://www.npmjs.com/package/@mojotech/json-type-validation https://www.npmjs.com/package/@mojotech/json-type-validation
- ledauphin 5y agowe use GraphQL for this purpose as well, but I'd also like to be able to validate across other boundaries. However, as I'm saying this, I wonder if I've been looking at this problem wrong. Since we already generate types from GraphQL schemas, maybe I should figure out how to use the same client side parser that's already in my GraphQL client, define a GraphQL schema for the types I'm interested in, and then just generate and use those types. One thing that doesn't necessarily give me is the ability to define custom parsers corresponding to custom types. At least, I think most of that sort of thing is usually done server side with GraphQL. So, thank you for the link and also the inspiration for considering an alternative.
- renke1 5y agoNot exactly what you want, I think, but there is zod [0]. I really would like to see nominal typing support in TypeScript. Currently, it's hard to validate a piece of data (or parse for that matter) once and have other functions only operate on that validated data. There are (ugly?) workarounds though [1]. [0]: https://github.com/colinhacks/zod https://github.com/colinhacks/zod [1]: https://gist.github.com/dcolthorp/aa21cf87d847ae9942106435bf47565d https://gist.github.com/dcolthorp/aa21cf87d847ae9942106435bf...
- iddan 5y agoIt is definitely possible as Flowtype got it right. I hope one day it will come to TypeScript as well
- brundolf 5y agoUse io-ts: https://github.com/gcanti/io-ts https://github.com/gcanti/io-ts You define a decoder schema, and then the resulting TS type gets automatically derived for you. You can then run data through the decoder, it will err if there's a mismatch, or return a value of the inferred type otherwise.