JSON to TypeScript in less than 1 second!

remojansen

Remo H. Jansen

Posted on July 23, 2024

JSON to TypeScript in less than 1 second!

Imagine that you are trying to integrate an HTTP API with a TypeScript client. Sometimes, SDKs and documentation are available, but other times, you are in the dark.

Let's imagine that we are fetching the following JSON file:

https://gist.githubusercontent.com/robertcedwards/8574169/raw/90c2d25d3ad5fd0b5f3a56b523e409ce7e0e9480/sample_nested.json
Enter fullscreen mode Exit fullscreen mode

The URL above returns the following JSON:

{ 
    "coffee": {
        "region": [
            {"id":1,"name":"John Doe"},
            {"id":2,"name":"Don Joeh"}
        ],
        "country": {"id":2,"company":"ACME"}
    }, 
    "brewing": {
        "region": [
            {"id":1,"name":"John Doe"},
            {"id":2,"name":"Don Joeh"}
        ],
        "country": {"id":2,"company":"ACME"}
    }


}
Enter fullscreen mode Exit fullscreen mode

Having to write TypeScript type definitions by hand for a JSON response like this can be time-consuming, this is why I have released a command line utility to save some time. You can call it using npx as follows:

npx dts-from-json <URL>
Enter fullscreen mode Exit fullscreen mode

You just need to replace <URL> with a URL that returns a JSON response:

npx dts-from-json https://gist.githubusercontent.com/robertcedwards/8574169/raw/90c2d25d3ad5fd0b5f3a56b523e409ce7e0e9480/sample_nested.json
Enter fullscreen mode Exit fullscreen mode

In less than 1 second, you will see the following in your terminal:

interface SampleNested {
  coffee: Coffee;
  brewing: Coffee;
}
interface Coffee {
  region: Region[];
  country: Country;
}
interface Country {
  id: number;
  company: string;
}
interface Region {
  id: number;
  name: string;
}
Enter fullscreen mode Exit fullscreen mode

If you wish to save the file, you just need to redirect stdout to a file:

npx dts-fromjson <URL> > types.d.ts
Enter fullscreen mode Exit fullscreen mode

Here are a few JSON files that you can use to test it:

You can also use local files by passing a path instead of a URL:

npx dts-fromjson <local-path-to-json-file>
Enter fullscreen mode Exit fullscreen mode

The dts-from-json module is available at npm. While this tool might not be perfect it can definitely save you some time.

I hope you enjoy it 🤓 Thanks for reading 💛

💖 💪 🙅 🚩
remojansen
Remo H. Jansen

Posted on July 23, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related