Classes in TypeScript

TypeScript supports most of the Object Oriented Programming concepts. One of them is Class. Class is a template which describes the structure of object which will instantiate it. Class is also a form of encapsulating methods and object properties together.
To create a class in TypeScript we can use following syntax:

class className{
//class body
}


Class can contain one of three or all three things:
1. Fields
2. Methods
3. Constructors


We can see from our below declaration, roleId and name are fields, getDetails() is a method, constructor(roleId: number, name: string)… is a constructor definition.

You can see this.name = name; statement inside constructor. This statement specifies, assign name variable to current instance’s name variable. this is a keyword here which will instruct compiler to point to current instance of the class.

Creating Class Object

You can create class object as following,

var objectName = new className([parameters]);

new is a keyword which creates new object of this class,
className([parameters]) will call constructor of this class.

Example of Class

Lets see a working example of basic class in typescript.

See the Pen TypeScript Classes by Code Topology (@codetopology) on CodePen.


Access Specifiers in TypeScript

Every language has specific set of access specifiers/scope specifiers which defined way in which class/object/method can be accessed. It controls visibility of its members.
Following access specifiers are supported in TypeScript:

Access SpecifierDescription
PublicThis specifies variable/class/method can be accessed publicly. This is a default access specifier.
PrivateThis specified variable/class/method can be accessed only inside class where it is declared.
ProtectedThis Specifies variable/class/method can be accessed in same class and in child classes which extended base class.

Static Keyword

Static fields/classes retain themselves till the complete execution of program. It can be accessed without object, we will use dot operator with class name to access static members.

Student.name;

Leave a Reply

Your email address will not be published. Required fields are marked *