TypeScript Classes

Author:

TypeScript Classes

TypeScript, considered the more advanced version of JavaScript, is an object-oriented language. So, it consists of OOP concepts such as classes and interfaces and many more. If you are learning TypeScript and are stumped in the middle by encountering the complex features of TypeScript classes, this detailed article might be able to clear any doubts you may have.

What are TypeScript Classes?  

Objects are entities used to represent real-world objects in OOP. Classes are used to create objects in programming.

Let’s use an automobile as an example to understand better. The components that make up the car are referred to as objects, and the vehicle is referred to as a class.

A built-in function in TypeScript facilitates the use of classes in programs. This is due to its support from ES6 and later versions. Classes were not supported in older versions of JavaScript.

Now that we’ve established the definition, let’s look at how to create TypeScript classes and their syntax:

Creating Class in TypeScript

The right syntax must be followed in order for the code to compile without minor mistakes. The syntax for creating classes is as follows:

Syntax:

class class_name { 

   //class scope 

}

The above syntax is used to define a class. A class definition usually contains the following:

  • Fields, which refer to the variables declared within the class.
  • Constructors, which allocate the memory of the objects.
  • Functions which are a crucial part of the class. The functions, also known as methods, are used to define the actions to be taken by the objects.

An Example of Typescript Class:

class Person { 

    ssn;

    firstName;

    lastName;

    constructor(ssn, firstName, lastName) {

        this.ssn = ssn;

        this.firstName = firstName;

        this.lastName = lastName;

    }

    getFullName() {

        return `${this.firstName} ${this.lastName}`;

    }

}

Class Inheritance

As a language that follows the majority of OOP principles, it is no wonder that TypeScript supports the inheritance feature.

Inheritance is a feature that allows new classes to be created from existing classes. Here the newly created classes are referred to as children or subclasses, while the class from which new ones are created are called the parent classes or superclasses.

The child classes ‘inherit’ all the properties of their parent classes along with their unique properties. Except for the private members and constructors, all other features are inherited.

The syntax of class inheritance in TypeScript is as follows:

Syntax:

class child_class_name extends parent_class_name

The ‘extends’ keyword is used to specify that the child-class inherits the properties from the specified parent class.

Another critical point to note is that TypeScript does not support multiple inheritances, meaning one subclass can inherit from only one superclass. 

Example:

The super class:

class Person {

    constructor(private firstName: string, private lastName: string) {

        this.firstName = firstName;

        this.lastName = lastName;

    }

    getFullName(): string {

        return `${this.firstName} ${this.lastName}`;

    }

    describe(): string {

        return `This is ${this.firstName} ${this.lastName}.`;

    }

}

The Subclass:

In the following code, the class is a sub-class that derives properties from that of the superclass.

class Employee extends Person {

    //..

}

Public, Private, and Protected Modifiers 

Data hiding or encapsulation is another valuable OOP feature that enhances the coding. Using access modifiers, the programmer can control the visibility of their program from other members of the same class or the whole program.

The access modifiers which are available in TypeScript are:

  • public 
  • private
  • protected

public Modifier:

If a data member is defined as public, it means it is universally accessible by other members in the class. It is the default mode of the members and is not necessarily required to define a member as public.

Example:

class Person {

    // ...

    public getFullName(): string {

        return `${this.firstName} ${this.lastName}`; 

    }

    // ...

}

private Modifier: 

The private data members are accessed only by the other members of the class. Even if they are subclasses, other members of the class will not be able to access them. The compiler will return an error if you try to use private members.

Example:

class Person {

    private ssn: string;

    private firstName: string;

    private lastName: string;

    // ...

}

protected Modifier:

The protected data member is similar to the private data member. The only difference is that their child classes’ members can access protected data members.

Example:

class Person {

    protected ssn: string;

    // other code

}

Other Concepts of Typescript Classes

Aside from inheritance and modifiers, let’s look at some of the other important concepts of TypeScript classes.

  • Static Methods

A static method is a method whose value is zero and gets incremented every time a new object is created. The static property is shared among all instances of a class.

The static keyword is used in declaring the static property.

Example:

class Employee {

    static headcount: number = 0;

    constructor(

        private firstName: string,

        private lastName: string,

        private jobTitle: string) {

        Employee.headcount++;

    }

}

In the above example, the value of headcount, which is a static property, is increased whenever a new object is created.

  • The readonly modifier

The readonly modifier is used in defining the property of the members of the classes as immutable or, in other words, permanent.

The readonly modifier is assigned in only two places:

  • In the property declaration.
  • In the constructor of the same class.

An example of readonly modifier is: 

class Spider {

  readonly name: string;

  readonly numberOfLegs: number = 8;

  constructor(theName: string) {

    this.name = theName;

  }

}

  • Accessors 

The accessors getter and setter are used in getting and setting the value of a variable in TypeScript to avoid redundancy.

Syntax:

get propName() {  

    // getter 

  },  

set propName(value) {  

    // setter

  }  

In TypeScript,

  • The getter method is represented by the keyword get. It is also known as an accessor. It retrieves the value of a variable.
  • The setter method is represented by the keyword set. It is also known as a mutator. The setter updates the value of the variable.

An example of accessors are as follows:

    // ... other code 

    public get fullName() {

        return `${this.firstName} ${this.lastName}`;

    }

    public set fullName(name: string) {

        let parts = name.split(' ');

        if (parts.length != 2) {

            throw new Error('Invalid name format: first last');

        }

        this.firstName = parts[0];

        this.lastName = parts[1];

    }

}

  • Abstract Classes

An abstract class is created to define the common properties of the classes that will be inherited from it later. The common properties may be, for example, age, name, etc.

To create an abstract class, use the term ‘abstract’ before the class name.

Syntax:

abstract class ClassName{

//variables declaration;

//abstract or non-abstract methods;

}

Within the abstract classes, abstract methods are introduced. The abstract methods are only signatures. The definition of the methods will be defined in the derived class.

For the other classes to use an abstract class, you need to inherit it and provide the implementation for the abstract methods.

An example of abstract class is as follows:

abstract class Employee {

    constructor(private firstName: string, private lastName: string) {

    }

    abstract getSalary(): number

    get fullName(): string {

        return `${this.firstName} ${this.lastName}`;

    }

    compensationStatement(): string {

        return `${this.fullName} makes ${this.getSalary()} a month.`;

    }

}

One last note before ending the article, the programs are shown in this is in TypeScript. These programs are converted into JavaScript programs during the compiling time.

Learn Basic Code for Free

Using classes in your program will reduce the complexity and redundancy in your program. We believe you were able to traverse around the various topics that come under TypeScript classes. However, if you’re brand new to coding, then try our free 5 Day Coding Challenge. On this short BootCamp, you will learn the basics of HTML, CSS and JavaScript. Register now through the form below. If you already know the basics, then have a look at our Full Stack Software Development programme.

Alejandro's Journey to Software Development

Welcome to the inspiring tale of Alejandro, an adventurous individual from Argentina who embarked on a transformative journey into the world of software development through Code Institute. His story is a testament to the power of determination and continuous learning. From Argentina to Ireland: A Leap of Faith Alejandro moved from Argentina to Spain in […]

How to Become a Software Engineer

If you are fascinated by the world of technology or curious about how software applications work, a software engineer career might be the perfect fit. In this guide, we look at the journey of becoming a software engineer, from the necessary qualifications to the steps that can lead you to success in the ever-evolving tech […]

What is NPM?

Staying on top of the latest tools and technologies is essential. One such tool that has become indispensable for developers is NPM, which stands for Node Package Manager. Whether you’re a seasoned developer or just dipping your toes into the coding world, understanding what NPM is and how it can enhance your development process is […]