DEV Community

Discussion on: How to create a type for complex JSON object in TypeScript?

Collapse
 
csandman profile image
Christopher Sandvik

If you're hitting an external API (without using someting like tRPC) your best bet is to do schema validation at runtime. You can always just assert that the values coming back match a structure you define as an interface, but if the endpoints change, you might not realize until your app starts breaking.

The tool I've seen to do this is zod. It's TS first approach lets you define a schema, and validate your data against it, and the data it returns will either throw an error if the structure is wrong, or return the data already statically typed.

No assuming the data is structured how you expect it, instead checking the structure and applying an interface all in one go!