Hacker News new | ask | show | jobs
by mrloba 1780 days ago
I like this approach a lot. I wonder if it's a good idea to keep the assertions in prod as well. I guess this is a trade-off between safety and convenience..

As a side note, what do people think about JSON schema? I find it quite verbose and cumbersome (compared to, say, typescript type definitions)

5 comments

> As a side note, what do people think about JSON schema? I find it quite verbose and cumbersome

Agreed. But if you want to have validation and autocompletion in most editors, it is still the way to go. We use it to validate JSON content files for a CMS [1]. It is a little repetitive in our case (e.g. the `:name`/`:description` keys are repeated), but not that bad. Newer versions of JSON Schema [2] have improved in that respect, but most editors (or plugins) and tooling in general is still based on older versions. So we have to stick with those for a while.

[1] https://github.com/frontaid/schema/blob/master/frontaid-sche...

[2] https://json-schema.org/specification.html

If you have to deal with JSON a lot, you might want to checkout https://www.schemastore.org/json/ which has schemas for a large number of file types.

I used https://github.com/ForbesLindesay/typescript-json-validator for a service I built recently. It parses TS types and turns them into a validator function - seems to work very well so far.

There’s a conversion of the type to JSON schema under the hood but I don’t have to worry about doing it by hand.

I've used JSON schema a fair bit for config files for provisioning infrastructure and its been great. For example I have a kubernetes clusters JSON file cleanly schematized which specs all the clusters I need (node pools, metadata etc), which I generate TS types from using 'json-schema-to-typescript', and then just iterate over these in pulumi. All I need to do is update the JSON file to update my infra, and the coding experience is brilliant with pretty much complete type safety.
I wouldn't write JSON schema definitions directly. Check out typebox. It lets you define a schema in memory and immediately have access to the types https://github.com/sinclairzx81/typebox

Combined with ajv you can even have more advanced custom validation with custom error messages.

It seems fine for validation, but when I want an IDL it seems to be vague in describing the indended data structure. This is in terms of cross platform dev and far from JS. It’s fine for describing the string like things, but when getting into sum types it doesn’t give more than `dependencies` to describe a tag descriminator. Going the other way, that doesn’t say more than both need to be there when the sum type is present.