Quantcast
Channel: Krzysztof Żuraw blog's RSS Feed
Viewing all articles
Browse latest Browse all 205

TypeScript abstract classes

$
0
0

Hello, Today I want to give you a blog post about abstract classes in TypeScript. What are they? Why you may need one? Or why you may not need it.

I assume that you have grasp of TypeScript and object oriented programming.

Let’s get started 🎉.

What are abstract classes

What exactly is abstract class? This concept is not bound only to TypeScript. Most of object oriented languages have concept of abstract classes. Abstract means that given class can be used to build other classes. For instance by inheritance. One of the important distinction between normal class is that you can’t instantiate abstract class.

abstractclassPoint{
    x:string;
    y:string;}classMarkerextendsPoint{}const point =newPoint();^ Cannot create an instance of an abstractclass.const marker =newMarker();

You may ask what is the difference here between interface and abstract class? The main one is that the latter can have implementation details. Let’s look at this example:

interfaceUser{
  name:string;getName();}abstractclassAbstractUser{
  name:string;getName(){returnthis.name;}}classUserClassextendsAbstractUser{}const user =newUserClass();
user.getName();

You can specify that interface User has to have get_name but you cannot provide it’s implementation in the same place like in example with abstract class.

Where abstract classes may come handy

If you want to share properties or methods between more classes. Like in this example:

abstractclassAbstractUser{
  name:string;getInfo(){returnthis.name;}}classEnterpriseUserextendsAbstractUser{
  enterpriseLogin:string;getInfo(){returnsuper.getInfo()+this.enterpriseLogin;}}classPasswordUserextendsAbstractUser{
  email:string;getInfo(){returnsuper.getInfo()+this.email;}}

You can make methods on class abstract too. Thanks to that all classes that implements this class need to have those methods implemented:

abstractclassAbstractUser{
  name:string;abstractgetInfo(){}}classWrongUserextendsAbstractUser{}^ Non-abstractclass'WrongUser' does not implement inherited abstract member 'getInfo'fromclass'AbstractUser'.

Summary and TL;DR

Abstract class in TypeScript can be created with abstract keyword before name of class. It is mainly used as a way of sharing implementations between classes that implements those abstract classes. You can find more info about them on TypeScript handbook.

If you have any questions about abstract classes please write to me: krzysztofzuraw(at)fastmail.com.


Viewing all articles
Browse latest Browse all 205

Trending Articles