Interfaces in typescript

Interface + Classes = How we get strong code reuse

Long Type Annotation

Given an object like so:

Say we want to implement a function that takes in such a type. We say, this parameter is called vehicle, and it takes in an object with property name of type string, year of type number, and whether it is broken…which is of type boolean.

Boy, this function annotation is really really long and tiring on the eyes

How to fix this long Annotation?

Creating an interface is like we are creating a type.

will tell us that we need a type like this:

now we can do this:

which is much easier on the eyes and fingers.

By definition, typescript gives us compile time checking. If we change true to 1 in oldCivic, we’ll get compile time checking for oldCivic, that it does not conform to the interface.

Functions around Interfaces

Is it important that Vehicles MUST have these properties? No, as long as Vehicle interface is a subset of what is provided in oldCivic, then we are okay.

In other words, as long as what we declared are included in the interface, then it is ok.

That is the ONLY QUESTION that is asked when we’re trying to check if the passed in object has the properties of the interface.

Let’s change the name Vehicle to Reportable. It is much more descriptive.
And change the function name.

Code Reuse with Interfaces

Notice we both have summary function that returns a string. They are both considered to be ‘Reportable’ types. So they can both be used in the parameter.

We can use a single interface to describe very different objects.