TypeScript: Classes and Interface

Jose Jithin
2 min readOct 9, 2018

TypeScript does wonders!!

“three persons in front of table” by rawpixel on Unsplash

TypeScript is purely object oriented with classes, interfaces and statically typed like C# or Java. Let’s see it in action with classes and interfaces. Hope you have already played with OOPs concepts.

Rather than explaining simply, I prefer to walk you through the examples.

How to create a simple class in TypeScript?

This is pretty much similar to what we do in Java.

What if we want static members inside class?

Just add ‘static’ keyword before member’s name and use class name to access the member.

How to restrict members of class with access modifiers?

Access modifiers are

  • public: universal accessibility.
  • private: accessible only within the class. (not even within objects)
  • protected: accessible within class and its children.

How to create an interface in TypeScript?

An Interface is just like an agreement between a class and interface itself. If class has to use interface, it has to assent to conditions from interface. i.e. class has to accept or implement members of interface. Now they will be together ever after. Lol!

Usually we see class implements interface. But following is how interface is implemented with a variable in TypeScript.

How Class implements Interface?

This is a usual “class - interface implementation” story.

How an Interface extends class?

This is quite interesting as it is a language specific feature of TypeScript. It’s possible that an interface can extend class.

What for?

  • to restrict usage of an interface.
  • This solution is used if we do not want any class can implement an interface.
  • Suppose interface ‘I’ extends class ‘C’. Then ‘I’ can be implemented only by ‘C’ or its children.
  • or if a class needs implement ‘I’, then it should extend ‘C’ first.

How can I do this?

Try and do experiments. Lemme know if you feel you can teach me another way or I can be improved.

Happy coding!

--

--