Convert json to TypeScript

While working on a Windows Store app I noticed I was writing TypeScript interfaces to get some syntax checking and code completion on JSON data received from an external service. In C# projects I’m used to use to get the C# classes for my JSON and than just deserialize it to those types. I quickly searched the web and realized there wasn’t a similar solution for TypeScript.

Solution was born. You just paste a block of JSON code into the text area and hit the generate TypeScript button to convert the piece of JSON to a TypeScript definition with interfaces.

Using the site

To use the result in you application you’ll have to add a “.d.ts”  file (declaration files) and just copy/paste the generated TypeScript from json2ts in there. You may have seen these files before, like for jQuery or KnockoutJS. These files only contain a description of types and are very useful when used next to a Javascript Library (for a lot of these have a look at DefinitelyTyped), but there are useful on the JSON result of a external service too.

Let’s assume there’s some 3rd party service you want to use in you application that return the following JSON:

This result is stored in the “result” variable. Now you can type “” in your code to use the date value. But, TypeScript can give use code completion and syntax checking in Visual Studio. When generates the interfaces for this piece of JSON it looks something like this:

You can see the relations between the various types. When you place this in a “.d.ts” file and reference this file in the TypeScript file you want to use the definition you get all the benefit of TypeScript.

Wrap up

The site isn’t tested very much and I’m pretty sure there are some bug in it. If you have a piece of JSON that isn’t converting properly, please send me an email ( ). If you have any questions or feature suggestion drop me a line too. I probably going to add some “advanced” features to set the module name and root object names.