DEV Community

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

lukeshiru profile image
LUKESHIRU • Edited on

If you want to have types based on a JSON you know (like an API response), you can use stuff like json2ts, and if you have that JSON in a file, you can just import it and use typeof:

import data from "./data.json";

export type JSONData = typeof data;
Enter fullscreen mode Exit fullscreen mode

If the API has swagger support, there are several tools that generate types from swagger files such as openapi-typescript.

The generic approach in your post doesn't look that useful from my point of view, mainly because you'll have to do a bunch of type checking and type casting inside that function to make it work as expected, so even if you didn't used any, is almost like you did with extra steps.

ankittanna profile image
Ankit Tanna Author

I liked this portal until it stopped creating relevant interfaces. Only a human mind currently can understand good logical interface.