- TypeScript is an Object Oriented Language and hence we can create classes, interfaces, objects etc. in TypeScript.
- We can create objects of the classes, hence classes encapsulates the data for the object.
- We use class keyword to create classes in TypeScript.
- Class name follows the rules same as variables.
- Class definition includes:
- Fields: A field is a variable declared in a class. They represents the properties of the object creates using the class. These fields can only be used by the objects of that class and their scope is limited to that class only.
- Constructors: Constructors are used to allocate memory for the objects of the class. We can also use constructors to assign values to the fields of the object. Please note that we can define only one constructor in a class, multiple constructor declaration is not allowed. A constructor is a function which can be parameterized.
- Functions: These are the operations or actions that an object can perform. They are also referred as methods.
- We do not use var keyword to declare fields in a class.
- this keyword refers to the current instance of the class. If the field name and constructor’s parameter names are same, we can use this keyword with fields to remove the ambiguity.
- We use new keyword to create an object of the class.
- Syntax: var objectName = new ClassName();
- In above piece of code, ClassName() invokes the constructor of the class. If the constructor has parameters, we can pass the value of those parameters from here. For example: var objectName = new ClassName(value1, value2,….);
- We access the field and methods of the class using the object followed by dot(.). For example,
- to access field: objectName.field1;
- to access function: objectName.functionName(parameterValue1, parameterValue2,…);
Syntax for creating class
class className{
// class fields and methods
}
Below is an example, where we create a class, define fields, constructor and function. We then create an object of this class, initialize the fields and then invoke the function.
class Car{
customername:string;
purchasedOn:string;
constructor(custName:string, date:string){
this.customername = custName;
this.purchasedOn = date;
}
purchaseDetails():void {
console.log(this.customername + " purchased a car on " + this.purchasedOn);
}
}
var car = new Car("Akanksha","28th Dec, 2018");
car.purchaseDetails();
Below is the output of above code

Other Related Articles
Interfaces in TypeScript
Interface and Classes in TypeScript
Inheritance in TypeScript
static keyword
instanceof Operator
Access Modifiers