Working with classes in typescript

classes in typescript

Working with classes in typescript is essential to write readable and reusable code. In this short article, we will understand classes in typescript in simplest way possible.

For the sake of simplicity, we will write all code in one ts file. You only need to have typescript installed globally to compile this ts file.

Writing a class in typescript:

Let’s first create a ts file named classes.ts, we will write a simple class Person with some properties.

Here, firstName and lastName are two properties. With typescript, we can define or restrict the type of value to be assigned. In this case, firstName and lastName can only be assigned string values.

string, number and boolean are primitive types available in typescript. More on types are on this link.

We can now instantiate this class and create as many objects as required.

To run this code, we will first compile the ts file into js with npx tsc classes.ts. Doing so, we should have a classes.js file. Now, we can execute classes.js with node classes.js command.

Adding constructor to typescript class:

So far, Person class is without a constructor. We can add one as follows:

A method named ‘constructor’ in a typescript class runs whenever an object of a class is created. Parameters defined for the constructor method, must be supplied at the time of instantiation.

In this case, the constructor takes fName, lName and age as parameters and initialize relevant properties.

Let’s have a look at the instantiation below:

Compiling and running the script now, should output this on console

Person { firstName: 'John', lastName: 'Doe', age: 22 }

Declaring and initializing properties within typescript constructor:

While above class looks more readable, there is a shorthand to declare and initialize the class properties within the class constructor. The class definition below is equivalent to the one defined earlier.

Please note, we now have an empty constructor body but it still do the job of assigning values to the class properties.

Adding a method to typescript class:

A function inside a class is called its method. In Person class, we might want to add a method which concatenates first name and last name and returns full name.

Compiling and running the script now should log ‘John Doe’ to the console.

Inheriting a class in typescript:

In a real world application, Person class will have varying implementations. An e-commerce application can have customer, admins, developers and many other entities relatable to Person. All these entities have some attributes like name, email and some methods like fullName in common. To deal with such a scenario, it is good practice to have a (kind of) abstract class which contains common attributes and behaviors.

For distinguished attributes and behaviors, we should define classes which extends the parent class and consist of the specific properties which are only relevant to this class. Let’s see how we create child classes in typescript or inherit a parent class.

The child class must call super() in its constructor to supply parameters to the parent class.

The customer class have a new property .i.e. orderIds. As orderIds array is only suitable for a customer entity, we have isolated it from a Person class.

In the Customer class, the property orderIds is being declared using constructor shorthand. By default, orderIds should be an empty array as declared by public orderIds: number[] = []

Since orderIds is only relevant to customer class, we need to have some methods in customer class to add and delete customer orders.

addOrderId is a customer class method, it takes an order id and push it to the orderIds property. : true | false part of the method definition is making sure that either a boolean true or false is returned.

Let’s see how we can create an object of customer class and add orders to it:

Running the code now should log something as following to the console:

Customer { firstName: 'John', lastName: 'Doe', age: 33, orderIds: [ 1245, 1235 ] }

Access modifiers in a typescript class:

In typescript, access modifiers are checked at compile time and not at runtime. following access modifiers can be used with class properties or methods:

Private access modifier ensures that the property or the method can only be used within the same class. Any attempt on accessing the private property or method from outside of the class and even in subclass will result in an error at compile stage.

Protected properties and methods can be accessed from the same class and also from the classes inheriting from this class.

Public access modifier, as the name suggests, can be accessed from class,subclass and outside of the class. By default, all the properties and methods of a class are public.

Tagged , ,

About Zohaib Shah

Passionate software engineer with expertise in Django, Laravel and NodeJS. Working with different SaaS based products and API connected apps. Get in touch
View all posts by Zohaib Shah →