Check out myAngular article series with live demos and Facebook group Angular - Advanced Topics

TypeScript and implicit interfaces

Torgeir "Tor" Helgevold
- JavaScript Developer and Blogger
Published: Thu Jul 02 2015

TypeScript introduces interfaces – a concept very familiar to developers with experience from languages like C# and Java.

Typically interfaces impose a firm contract on the objects implementing them. This allows us to treat the object like it's of a specific type, constrained by the interface definition.

However, in JavaScript we are often dealing with anonymous objects of no fixed type. Luckily, TypeScript will accept anonymous objects as valid implementations of interfaces as long as the object signature matches the interface.

Does this mean the entire object has to match the interface exactly? No, it's ok if the object is a superset of the interface. This is a nice benefit since it allows us to define interfaces for existing objects without having to manually convert them to a new type.

Below is an example of implicit conversion of an anonymous object to an interface.

getBooks():Array<Book>{ return [ {title: 'Title1', publisher: 'Publisher1', price: 100, pages: 100}, {title: 'Title2', publisher: 'Publisher2', price: 200, pages: 50}, {title: 'Title3', publisher: 'Publisher3', price: 300, pages: 200} ]; }

interface Book { title: string; publisher: string; price: number; }

The above code allows the returned objects to identify as Book objects because of the implicit implementation of the Book interface.

It's important to remember that interfaces are not natively supported by JavaScript though.

This means that this is essentially just a compiler trick to impose a contract on the object at compile time. The transpiled JavaScript object will be of type “regular” Object.

In JavaScript, no new Book type will be created. All the original properties will be accessible on the returned object – even the “pages” property not defined by the interface.

The lack of interface support in JavaScript may make this seem less useful, but I still think there is some value in trusting that objects will adhere to a contract, even if it's just enforced at compile time.

If you liked this article, share it with your friends on social media:

We also have a new Facebook group about advanced Angular topics.

I invite you to follow me on twitter