TypeScript Class:
As we discussed in earlier tutorials that TypeScript supports object-oriented programming concepts like classes, interfaces, etc. Class acts as a blue print or template for creating objects. It provides state and behaviour for its objects. A class is used to encapsulate the data for the object.
Syntax:
class class_name {
//field
//constructor
//function
} |
class class_name {
//field
//constructor
//function
}
Typescript creating objects:
The new keyword followed by the class name is used to create an instance of the class.
var objectName = new className([ arguments ]) |
var objectName = new className([ arguments ])
Example:
class Employee {
//field
name:string;
//constructor
constructor(name:string) {
this.name = name;
}
//function
display():void {
console.log("Employee Name: "+this.name);
}
}
//create an object
var obj = new Employee("Jai");
//access the field
console.log("Employee Name: "+obj.name);
//access the function
obj.display(); |
class Employee {
//field
name:string;
//constructor
constructor(name:string) {
this.name = name;
}
//function
display():void {
console.log("Employee Name: "+this.name);
}
} //create an object
var obj = new Employee("Jai"); //access the field
console.log("Employee Name: "+obj.name); //access the function
obj.display();