Because of this I prefer runtypes [1], because it's much more simple to get my desired behavior. My only gripe is that errors aren't all that descriptive.
I guess I could write a function to pipe/fold into the type, throwing a descriptive error if something fails, but I like the simplicity of runtypes.
Edit: I just discovered io-ts ErrorReporter [2]. That's way better than my solution, and I'm considering switching now!
1: https://github.com/pelotom/runtypes
2: https://github.com/gcanti/io-ts/blob/master/src/ThrowReporte...
But once you have those set up, it's an easy breeze, and the benefits are enormous. Our helper-method with the hopefully self-explanatory name "validateOrThrow<T>(t:TypeGuardForT)" is essentially called at every point where there is some form of incoming external data, and the amount of debugging-headaches that have simply disappeared because of this is mind-blowing.
[1] https://github.com/epoberezkin/ajv
[2] https://www.typescriptlang.org/docs/handbook/advanced-types....
The problem is that a lot of the things you want to validate aren't easily expressible as typescript types (e.g., valid email address, make sure two fields are always the same length, etc). If json schema are more expressive you want to use that as your source to generate the typescript interface instead of the other way around.
https://github.com/gristlabs/ts-interface-builder
https://github.com/gristlabs/ts-interface-checker
Example: https://github.com/alangpierce/sucrase/pull/468/files
- the typescript interfaces: https://www.npmjs.com/package/json-schema-to-typescript
- the runtime checks with AJV
So you have no duplication and you're type safe.
Write your interface in json or text proto then build it to ts interfaces and runtime checks.
Typescript doesn't support macro currently, so code generation is the only way to programmatically create 'type-checked' code.
Some cli-tool and library I'm using (available on npm):
tsc-macro: https://github.com/beenotung/tsc-macro
gen-ts-type: https://github.com/beenotung/gen-ts-type
ts-type-check: https://github.com/beenotung/ts-type-check
Let's say I have a simple interface with a few fields. I want to make sure incoming JSON conforms to that interface.
I realize at runtime the interface isn't there, but is there some tool I can use to compile a utility to check JSON against an interface without having to write a duplicative JSONSchema or something else?