3 ms·
Just curious, is there a way to define typed DTOs or things like Pydantic models, and then parse blobs of JSON into said classes, all leveraging the type annota
by sk0g 3y ago
Just curious, is there a way to define typed DTOs or things like Pydantic models, and then parse blobs of JSON into said classes, all leveraging the type annotations?
I know it all gets compiled away in JS and all, but Pydantic is surprisingly ergonomic to use and type hints are sort of a suggestion, albeit available at runtime.
Closest I've seen is Zod, but the syntax looks horrendous IMO. Maybe you look past it eventually though.
- MatthiasDev 3y agoType reflection with TypeScript is fairly limited at the moment, though what you are describing can be done with decorators. I have made such a library myself: https://github.com/decoverto/decoverto https://github.com/decoverto/decoverto Another library would be https://github.com/typestack/class-transformer https://github.com/typestack/class-transformer
- darken 3y agoAssuming I understand you question: you can define an interface to describe what an object parsed from JSON contains, and then cast your raw JSON-parsed object into that type. The casting doesn't guarantee the JSON from your server fits the interface, but it WILL ensure any downstream use is correct, and also enable auto complete for its fields (assuming your IDE supports it). I've been using JavaScript on and off for nearly 20 years, and TypeScript is a massive improvement.