Skip to content

Initialize a Typescript Interface with JSON

February 20th, 2017 - Software(1 min)

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:

export interface PathInterface {
  path: string
  enabled: boolean
}

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:

pathItem: PathInterface;

constructor() {
  pathItem = {path: '/some/interesting/path', enabled:true}
}

Simple.

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

const d = { path: '/some/interesting/path', enabled: true }
console.log(d['path']) // prints '/some/interesting/path' (without the quotes)
console.log(d.path) // prints '/some/interesting/path' (without the quotes)

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,

Share on
Reddit
Linked in
Whatsapp

A little experiment: