Scripts by benjaminmodayil

Generate TS Interfaces from JSON input

Hi everyone,

Just made this quick script and thought I'd share. My company is updating our codebases to use TypeScript and wanted a way to quickly generate interfaces from JSON input. I'm usually right clicking and copying parts of API responses in the Network tab to pick out the JSON and manually type things out. Now I just copy the JSON, paste into Kit, and then save a few moments of my time.

Script

// Title: Generate types
// Description: Paste your JSON in and get your Interfaces straight to your clipboard
// Author: Benjamin Modayil
// Twitter: @24props
let {json2ts} = await npm('json-ts')
let schema = await arg("What is the schema?");
await copy(`${json2ts(schema)}`)
notify({
title: 'Interfaces copied to the clipboard',
message: "Paste your interfaces into a text editor"
})
exit() // needed otherwise scriptkit hangs open

I haven't tested the script that much yet, but something that could be tweaked would be wrapping json-ts in a try/catch and outputting a different notification depending on the result.

Another thing to note is that the output from json-ts could always be improved from the developer using the script. I would assume for json-ts that it's pretty hard to generate union types without more data to comb through and it's up to the developer to determine when you might need flexibility number | string or strictness from something like "success" | "error" | "warning". Also, from the example output below, json-ts generates the property previous as null, based on the data provided, but I'm guessing it's actually supposed to be a string like next. All this to say: "use at your own discretion".

Example

Go to this Pokemon API JSON link, copy JSON, paste into script, paste into editor, and see the below output:

interface IRootObject {
count: number;
next: string;
previous: null;
results: IResultsItem[];
}
interface IResultsItem {
name: string;
url: string;
}
Discuss Post