Interfaces in TypeScript

By Dawid on (tags: interface, TypeScript, categories: code)

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 object

Note the use of the symbol after color - this marks a member as being optional. In the compiled JavaScript you will not see any information’s about defined interface as those are only compile time construct and have no effect on the generated code.

Describing and Indexable object

I thing that all of use used and object in JavaScript – {} – to map from set of strings to set of values. We can use interface here when those values are of the same type. This will describe that indexing  into an object always produce values of a certain type.

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:

Extending interface

There is one more nice thing about interfaces in TypeScript – they can be extended. It’s quite simple: