Initialize a Typescript Interface with JSON

Posted by in Software

TL;DR: You can initialise a typescript interface using JSON objects.

On my quest to load and save objects as JSON, I found that you can convert a JSON object to an interface via something called type assertion. Basically, if you have an interface:

you can load a JSON object via JSON.parse(json) straight to an instantiation of the interface. Then, you can use the said instantiation in e.g. a component.

Now, all is nice, but what if you want to initialise an instance of the PathInterface interface? That’s simple. You just assign a dict:

Simple.

In hindsight, you can see that you can address the dict in two ways:

It then makes sense you can assign JSON to an interface.

Note: The typescript compiler will throw an error if it cannot figure out the cast.

HTH,


A little experiment: If you find this post and ad below useful, please check the ad out :-)