4 ms·
re: TypeScript doing "this number has to be less than 120".. As a fun aside in fact you _can_ write this kind of type today (since 4.5 when they added tail-recu
by dimitropoulos 4y ago
re: TypeScript doing "this number has to be less than 120".. As a fun aside in fact you _can_ write this kind of type today (since 4.5 when they added tail-recursion elimination on conditional types). You can even do things like `Range<80, 120>` to clamp to a range. If something like "Negated types" ever happens (https://github.com/Microsoft/TypeScript/pull/29317 https://github.com/Microsoft/TypeScript/pull/29317) it'll make even more options available.
Also, if you haven't checked it out, typescript-json-schema has some REALLY powerful validation it can do for things like your example (https://youtu.be/HHTDCY5uh_M?t=1379 https://youtu.be/HHTDCY5uh_M?t=1379). You can do stuff like this
export interface Shape {
/**
* The size of the shape.
*
* @minimum 0
* @maximum 120
* @TJS-type integer
*/
size: number;
}
and regarding the part about generating JSONSchema from TypeScript files. I totally know what you mean, I think that approach really has great potential, but there's still nothing _enforcing_ that contract. If you care about the frontend and backend always being in sync (i.e. through deploys of the backend/frontend, but also in situations like many people find themselves in with dashboard web apps where users many not often refresh their page through many backend and frontend deploys), then you'll probably benefit from a tool like protobuf or GraphQL or any others that tries to help with this validation.
- com2kid 4y ago> Also, if you haven't checked it out, typescript-json-schema has some REALLY powerful validation it can do for things like your example (https://youtu.be/HHTDCY5uh_M?t=1379 https://youtu.be/HHTDCY5uh_M?t=1379). You can do stuff like this Oh wow I didn't realize TS JSON Schema was capable of all that! > but there's still nothing _enforcing_ that contract. Sure there is, the schema on my REST endpoint. Express and AJV check all messages coming in. It requires changes be non-breaking changes of course, new fields need to be optional, same as protobuf. Removing a field means making it optional, removing it from all calling code, then removing it from the schema entirely. Real pain, but that is the price you pay if you want required fields. Only really doable if you can also control all the code, but since I'm working on internally facing services only, not an issue. :)