Classes in TypeScript is a template for creating objects. The class defines the data (fields or properties) and the operations (methods) that we can perform on that data. We can create many objects using a single class. In this tutorial, we will learn how to create classes in typescript. How to add Properties and methods to a class, create objects from the class etc.
Table of Contents
Creating Classes in TypeScript
To create a class we need to use the class
keyword followed by { }
. Inside the brackets, we will add the properties, methods, and a special constructor method.
The following is an empty class.
1 2 3 4 | class Person { } |
A class declaration can contain the following
- Fields: A field (or property) is a variable that we declare in the class. It will contain the data of the class.
- Functions or Methods: The Operations that the objects can perform. They represent the behavior of the class.
- Constructor: is a special function that is invoked every time we create a new object from the class.
Adding Fields to Class
The fields (properties) hold the data of the class. Adding a field is similar to declaring the variables. But without the use of let
, var
& const
keyword.
In this example, we have added two fields firstName
& lastName
. Both the properties are of type string
.
1 2 3 4 5 6 | class Person { firstName:string="" lastName:string="" } |
Note that Typescript since version 2.7 raises an error if class properties are not given an initial value. Refer to the StrictPropertyInitialization config option for more detail. Hence the above code results in a compiler error (Property ‘firstName’ has no initializer and is not definitely assigned in the constructor).
Creating objects from Class
The class acts as a template for creating objects. We can create multiple objects using the same class. To create a new object use the new
keyword followed by the name of the class and then brackets ( )
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | class Person { firstName:string="" lastName:string="" } let p1 = new Person(); p1.firstName="Jon" p1.lastName="Snow" console.log(p1) //Person: { "firstName": "Jon", "lastName": "Snow" } let p2 = new Person(); p2.firstName="Samwell" p2.lastName="Tarly" console.log(p2) //Person: { "firstName": "Samwell", "lastName": "Tarly" } |
Providing initial value to Properties
There are two ways by which you can provide an initial value to the property.
One is in line with the declaration of property fields. In this example, we have defined the class properties with an initial value. The issue with this approach is that every object that we create will be having the same value for firstName
& lastName
1 2 3 4 5 6 7 8 9 10 11 12 | class Person { firstName:string="Jon" lastName:string="Snow" } let p1= new Person() let p2= new Person() console.log(p1) //Person: { "firstName": "Jon", "lastName": "Snow" } console.log(p2) //Person: { "firstName": "Jon", "lastName": "Snow" } |
You can also call some functions or methods etc.
1 2 3 4 5 6 7 8 9 10 11 12 | class Person { createdAt= new Date() } let p1= new Person() let p2= new Person() console.log(p1) //Person: { "createdAt": "2022-08-16T15:46:26.255Z" } console.log(p2) //Person: { "createdAt": "2022-08-17T15:30:25.145Z" } |
The preferred way is to use the constructor function, which allows us to pass different values when we create an object from it.
Constructor function
A constructor is a special function of the class that is automatically invoked when we create an instance of the class. We use it to create & initialize the instance of the class.
The constructor method in a class must have the name constructor. A class can have only one implementation of the constructor method.
In this example, we have created an empty Person
class with a constructor function. The constructor function prints Constructor is called
every time it is invoked. As you can see from the example, every time we create a new object with a call to new Person()
, the constructor is invoked.
1 2 3 4 5 6 7 8 9 10 | class Person { constructor() { console.log("Constructor is called") } } let p1= new Person() //contructor is called let p2= new Person() //contructor is called |
We use the constructor function to initialize the instance of the class. The constructor function is just like any other function and can accept any number of arguments. The following constructor takes two arguments i.e. firstName & lastName.
1 2 3 4 5 6 7 8 9 10 11 | class Person { firstName:string; lastName:string; constructor(firstName:string, lastName:string) { this.firstName=firstName; this.lastName=lastName; } } |
You can create an instance from the class by invoking the new
operator on the Person
class. In the argument, we will pass the firstName
& lastName
. The new Person
will invoke the constructor function associated with the class Person
passing the arguments to it.
1 2 3 4 5 6 7 | let p1= new Person("Jon","Snow") let p2= new Person("Samwell","Tarly") console.log(p1) //Person: { "firstName": "Jon", "lastName": "Snow" } console.log(p2) //Person: { "firstName": "Samwell", "lastName": "Tarly" } |
The constructor method creates the instance of the object with the properties defined in the class. We can access that instance by using the this
inside the constructor. We use that to initialize the properties of the current object. Once finished constructor function returns the new object.
Methods
A function declared in a class is called a method. The methods represent the behavior of the class.
Creating a method is similar to creating a function. In the following example, we getName
method returns the name of the Person. Inside the method, we can use the this
keyword to access the fields and other methods of the current instance of the object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | class Person { firstName:string; lastName:string; constructor(firstName:string, lastName:string) { this.firstName=firstName; this.lastName=lastName; } // Example of method getName() : string { return this.firstName + " "+ this.lastName } } let p= new Person("Jon","Snow") console.log(p.getName()) //Jon Snow |
Class declarations are not hoisted
The class declaration in TypeScript (and also in JavaScript) is not hoisted. i.e. you cannot use class before you declare it. The following code results in an error. You can read more about Hoisting in JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | let p= new Person("Jon","Snow") //Class 'Person' used before its declaration. class Person { firstName:string; lastName:string; constructor(firstName:string, lastName:string) { this.firstName=firstName; this.lastName=lastName; } } |