JSON to TypeScript Types
Turn a JSON API response into TypeScript interfaces, with nested objects extracted and array members named sensibly.
Turn an API response into TypeScript interfaces, with nested objects and arrays named for you.
Types
2 interfaces generated
Profile
ApiResponse
Types are inferred from one sample, so an optional field missing from this response will not appear. Check the API docs for fields that are sometimes absent.
export interface ApiResponse {
id: number;
name: string;
active: boolean;
avatar?: null;
roles: string[];
profile: Profile;
}
export interface Profile {
city: string;
followers: number;
}About the json to typescript types
Typing an API response by hand is tedious and it is where typos live. Pasting a real response and generating the interfaces takes seconds and gets the field names exactly right, including the ones in a casing you would not have guessed.
Nested objects become their own named interfaces rather than inline types, and plural keys are singularised so an array called users produces a User type.
How to use it
- 1Paste a real response from the API.
- 2Name the root type.
- 3Decide whether null fields should be optional.
- 4Copy the interfaces into your project.
Questions
Are the generated types guaranteed correct?
They describe the sample you pasted. A field that is optional but present in this response will be typed as required, and a field that is sometimes a different type will only show the type it had here.
Why are null fields marked optional?
A null in a sample usually means the field is sometimes absent or empty. Marking it optional is the safer assumption, and you can turn that off.
Does this validate data at runtime?
No. TypeScript types disappear at compile time. For data from an API you do not control, add runtime validation as well, since json() returns any and will happily hand you the wrong shape.
What happens with an empty array?
It becomes unknown[], because an empty array carries no information about what it holds. Paste a response with data in it for a useful type.