In TypeScript interfaces are used to descript a type. Classes and functions are used to implement behaviour while interfaces are providing information's about shape of the data. All of the type information’s are removed from TypeScript program during compilation there is no runtime overhead and we can freely add type data.
To be honest with you interfaces are like Swiss army knife. We can use them in following cases:
- describing an object
- describing an indexable object
- ensuring class instance shape
- ensuring the static shape of a class or constructor object
Describing and Indexable object
Take a look at this example:
Thanks to the interfaces you can be sure that in variable “c” will be stored object of Car.
Ensuring class instance shape
Lets imagine that we have following interface describing car:
Now we can use to to describe car object:
Ensuring shape of an object
Lets assume that we want to describe return type of an function. First we need to define an interface:
Now we can define function like that:
There is one more nice thing about interfaces in TypeScript – they can be extended. It’s quite simple: