Data conversion guides

Generate TypeScript interfaces from sample API records

·

Start with several realistic records from the API that feeds your listing screen. Samples with shared properties, missing keys and mixed arrays give the converter more information about what your code will receive.

JSON to TypeScript Interface

Generate declarations for the listing response

Choose Load example, enter ListingResponse as Root declaration name and keep Interfaces for objects. Choose Generate TypeScript. The root is an array type alias, and its elements and their contact objects have their own named interfaces.

Find contact followed by a question mark and an object type union with null. The second record supplies null. The third omits the property. Find the labels property with type (string | number)[]. The parentheses place the union inside the array type.

The mixed listing response from Load example
[
  {"id": 41, "contact": {"email": "one@example.com"}, "labels": ["new"]},
  {"id": 42, "contact": null, "labels": []},
  {"id": 43, "labels": [1, "sale"]}
]

TypeScript Handbook, object types and optional propertiesTypeScript Handbook, everyday types

Check quoted keys and choose a declaration style

Replace the example with {"order-id":7,"ship to":{"city":"Lima"}}. Generate again. The keys retain their spaces and punctuation through quoted property declarations. Access the resulting property with bracket notation, such as order["order-id"].

Choose Type aliases to generate an alias for each object. Make every property optional when you want a draft for partial updates. Optional keys such as constructor and toString include their inherited JavaScript types. Check ownership before treating these keys as fields supplied by the API.

TypeScript Handbook, object types and optional propertiesTypeScript Handbook, everyday types

Check the generated types in your project

Download types.ts and compile it with your project's strict TypeScript settings. Assign a known response to the exported type. Check how your code narrows unions and reads optional fields before it uses them.

An empty sampled array gives unknown[]. Dates carried as JSON strings become string. TypeScript types are checked at compile time. Use runtime validation for incoming JSON that must meet a contract.

TypeScript Handbook, everyday types

Common questions

Does a JSON integer become bigint?

JSON numbers become TypeScript number. Ask the API for strings when IDs must preserve decimal precision beyond JavaScript's safe integer range.

Can nested objects have the same key name?

Yes. Generated declaration names are made unique when two objects would otherwise have the same name. The original JSON property names are preserved.

Sources

Put it into practice.

Related guides