Open In App

TypeScript class

Last Updated : 15 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

TypeScript classes play a crucial role in creating robust and maintainable code. In this article, we’ll learn TypeScript classes, explore their features, and learn how to optimize them for better search engine ranking. Typescript is an open-source programming language built over Javascript, also known as the Superset of Javascript. Typescript has more features when compared to Javascript. It supports Object-oriented programming features like classes, Interfaces, Polymorphism, etc. 

Syntax to declare a class: 

class class_name{
field;
method;
}

What Are Classes?

In TypeScript, classes are blueprints for creating objects. They encapsulate data (properties) and behavior (methods) into a single unit. By defining classes, you can organize your code, promote reusability, and enhance readability.

Key Components of TypeScript Classes

  1. Methods: Functions defined within a class that perform specific actions.
  2. Constructors: Special methods called when an object is created from a class. Constructors initialize class properties.
  3. Properties: Variables associated with a class instance.
  4. Inheritance: The ability to create new classes based on existing ones, allowing code reuse and specialization.

Example: Simple Class Declaration and Definition

javascript
class Person {
    constructor(public name: string, public age: number) {}

    greet(): void {
        console.log(`Hello, I'm ${this.name} and I'm ${this.age} years old.`);
    }
}

const john = new Person('Rahul', 22);
john.greet(); // Output: "Hello, I'm John and I'm 30 years old."

Output:

[LOG]: "Hello, I'm Rahul and I'm 22 years old." 

Access Modifiers (public, private, and protected)

  • public: Properties and methods are accessible from outside the class.
  • private: Restricts access to within the class itself.
  • protected: Allows access within the class and its subclasses.

Constructors in TypeScript

constructor is a special method within a class that is automatically invoked when we create an instance of that class. Its primary purpose is to initialize the properties of the current instance. In TypeScript, constructors allow us to set up the initial state of an object.

Example:

javascript
class Person {
    constructor(public name: string, public age: number) {
        // Initialize properties
    }
}

const john = new Person('Uday', 20);
console.log(`Name: ${john.name}, Age: ${john.age}`);

Output:

[LOG]: "Name: Uday, Age: 20" 

Explanation:

  • We define a Person class with two properties: name and age.
  • The constructor takes two parameters (name and age) and assigns their values to the corresponding properties.
javascript
// converted javascript code
var Student = /** @class */ (function () {
    function Student(code, name) {
        this.studName = name;
        this.studCode = code;
    }
    Student.prototype.getGrade = function () {
        return "A+";
    };
    return Student;
}());

Objects in TypeScript

Objects An object is an instance of class which contains set of key value pairs. It’s value may be scalar values or functions or even array of other objects. 

Syntax of an Object looks like the code below: 

javascript
// simple object code in javascript
let object_name = { 
   key1: value,  
   key2: function() {
      //functions 
   }, 
   key3:[content1, content2] //collection  
};

An object can contain scalar value, functions and structures like arrays and tuples. Let’s see with simple example: 

javascript
// simple javascript code
let person = {
   fName:"Mukul", 
   lName:"Latiyan", 
   Hello:function() {  }  //Type template 
} 
person.Hello = function() {  
   console.log("Hello "+person.fName)
}  
person.Hello()

Output:  

javascript
// typescript object example
var person = { 
   fname:"Mukul", 
   lname:"Latiyan"; 
}; 
var hello = function(obj: { fname:string, lname :string }) { 
   console.log("first name :"+obj.fname) 
   console.log("last name :"+obj.lname) 
} 
hello(person)

Output: For creating Instance Objects. To create an instance of the class, use with the new keyword followed by the class name. To allocates memory for objects with the help new during runtime. Like: 

javascript
let object_name = new class_name([ arguments ])

In order to create an instance of an object we can do something like the code below. 

javascript
let obj = new Student();  

Accessing Attributes and Functions: A class’s attributes and functions can be accessed by the object. With the help of ‘ . ’ dot notation or bracket notation([”]) we access the data members of a class.

//accessing an attribute 
obj.field_name or obj['field_name']

//accessing a function
obj.function_name()

Consider the code below: 

javascript
// typescript code
class Car { 
   //field 
   engine:string; 
   
   //constructor 
   constructor(engine:string) { 
      this.engine = engine 
   }  
   
   //function 
   display():void { 
      console.log("Function displays Engine is  :   "+this.engine) 
   } 
} 

//create an object 
var o1 = new Car("geeks")

//access the field 
console.log("Reading attribute value Engine as :  "+o1.engine)  

//access the function
o1.display()

After compilation this code will be converted into the javascript shown below: 

javascript
// converted javascript code
var Car = /** @class */ (function () {
    //constructor 
    function Car(engine) {
        this.engine = engine;
    }
    //function 
    Car.prototype.display = function () {
        console.log("Function displays Engine is  :   " + this.engine);
    };
    return Car;
}());
//create an object 
var o1 = new Car("geeks");
//access the field 
console.log("Reading attribute value Engine as :  " + o1.engine);
//access the function
o1.display();

Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads