←back to thread

Parse, don't validate (2019)

(lexi-lambda.github.io)
398 points declanhaigh | 3 comments | | HN request time: 0.699s | source
Show context
ckdot2 ◴[] No.35054435[source]
Please, don't write your own JSON parser/validator. There's JSON Schema https://json-schema.org which has implementations in most languages. You can valiate your JSON by a given, standardized JSON schema file - and you're basically done. After the validation, it's probably good practise to map the JSON to some DTO and may do some further validation which doesn't check the structure of the data but it's meaning.
replies(2): >>35054491 #>>35055093 #
mirekrusin ◴[] No.35054491[source]
Json schema doesn't have relation with static type system, ie. in typescript it's much better to use composable, functional combinators at i/o boundaries only and don't do any extra checks anywhere where type system provides guarantees.
replies(2): >>35054548 #>>35054555 #
1. bertrand-caron ◴[] No.35054555[source]
For anyone using both TypeScript and JSON schemas, but wanting to use TypeScript as the source of truth, I highly recommend the following library: [ts-json-schema-generator](https://github.com/YousefED/typescript-json-schema).

It does exactly what it says in the box: turns your TypeScript `types` / `interface` into machine-readable JSON schemas.

The library has a few open issues (does not deal well with some edge cases of composing Omit<> on sum types, and does not support dynamic (const) keys), but compared to manually writing JSON schemas, it's been amazing!

EDIT: I should add that the library supports adding further type constraints that are supported by JSON Schema but not by TS by using JSDoc (for instance, pattern matching on strings, ranges on numbers, etc.).

replies(2): >>35054767 #>>35054787 #
2. mirekrusin ◴[] No.35054767[source]
Adding extra transpilation step doesn't sound like a great solution.

It also doesn't support inlined assertions, referring to existing classes, custom validations, opaque types etc.

3. kristiandupont ◴[] No.35054787[source]
I generally prefer Zod but in cases where I for one reason or another have to rely on JSON Schema, I use this package: https://www.npmjs.com/package/as-typed which infers TS types directly from a such. No extra build steps required. I then use AJV for runtime validation.