Objects
Consider the following TypeScript code:
Seeing this error leads us to recall that TypeScript relies on duck typing to define its types in a structural manner. So TypeScript infers the type of band
to be not only an object, but importantly, an empty object.
We can prove TypeScript infers the type based on the object's structure (i.e., its property names and their types) by trying to assign a differently structured object.
In this example, we get an error because the property types must match:
The property names must also match:
When declaring a new object, you can explicitly annotate the object's type using the following notation:
This way of type annotating an object literal is uncommon because of an inherent limitation.
Take the following example, where we have two objects of the same type:
We can immediately recognize some issues with this code. For one, we now have duplicate types. Secondly, our types are out of sync — meaning if we want to make a change to the type in one place, we must update all other instances where that same object literal type annotation is used since they are declared independently.
Last updated