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.
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.