JSON to TypeScript in less than 1 second!
Remo H. Jansen
Posted on July 23, 2024
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
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"}
}
}
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>
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
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;
}
If you wish to save the file, you just need to redirect stdout
to a file:
npx dts-fromjson <URL> > types.d.ts
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>
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 💛
Posted on July 23, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.