Generate TypeScript interfaces from JSON
JSON (JavaScript Object Notation) has no formal concept of strict types. It only supports primitive values (strings, numbers, booleans, null) and structures (objects, arrays). When converting an arbitrary JSON payload from a REST API into strict TypeScript interfaces, the compiler has to guess the types using Type Inference.
Type inference becomes incredibly complex when dealing with arrays of objects.
If an array of user objects has a key "age" that is a number in the first object, but missing entirely in the second object, a smart type inferencer must scan every object in the array before making a decision. It will then mark the field as optional: age?: number;.
Similarly, if a field is a string in one object but a number in another, it will infer a union type: string | number.
To generate these types, this tool parses the JSON into an Abstract Syntax Tree (AST). It recursively traverses every node, gathering a list of all possible data types observed for every single object key across the entire document.
It then runs a reduction algorithm to squash those lists down into a minimal, clean set of TypeScript interfaces. This prevents generating hundreds of duplicate nested interfaces if the same object structure appears in multiple places in the JSON.
If a JSON array contains two objects: [{ 'status': 200 }, { 'status': 'OK' }], how should a TypeScript inferencer type the 'status' field?