Open In App

How to use class syntax in Typescript ?

Improve
Improve
Like Article
Like
Save
Share
Report

Classes: The class keyword was introduced in ES2015. TypeScript fully supports ‘class’ keyword. classes are a template for creating objects. A Class is a user defined data-type which has data members and member functions. Data members are the data variables and member functions are the functions used to manipulate these variables and together these data members and member functions defines the properties and behavior of the objects in a Class.

Syntax: 

class class_name {
  field;
  methods;
}

In the above syntax of class in TypeScript we just use class keyword along with class_name (you can give any name to class as per your choice or as per camelCase) and use curly braces to define fields (variables) and methods(functions).

Example 1: In the below example we create class (Gfg) and  declare fields along with constructor and function or method and by creating object of that Gfg class we are accessing fields and methods through that object.

Javascript




class Gfg {
    // Fields
    gfgid: number;
    gfgrole: string;
  
    // Constructor call
    constructor(id: number, role: string) {
        this.gfgid = id;
        this.gfgrole = role;
    }
  
    // Method
    getGrade(): string {
        return "Employee track record is A+";
    }
}
  
const gf = new Gfg(10, "front-end developer");
console.log(`Id of gfg employee is :${gf.gfgid}`);
console.log(`role of gfg employee is :${gf.gfgrole}`);
gf.getGrade();


Output: 

Id of gfg employee is : 10
role of gfg employee is : front-end developer
Employee track record is A+

The example declare a Gfg class which has two fields that is gfgid and gfgrole and a constructor which is special type of function which is responsible for variable or object initialization. Here it is parameterized constructor(already having the parameters). And this keyword which refers to the current instance of the class. getGrade() is a simple function which returns a string.

Example 2: In the below example we create class Geeks  and  declare function or method and by creating object of that Geeks class we are accessing method of class through that object.

Javascript




class Geeks{
     getName() : void {
        console.log("Hello Geeks");
    }
}
  
const ad = new Geeks()
ad.getName();


Output: 

Hello Geeks

Reference: https://www.typescriptlang.org/docs/handbook/classes.html



Last Updated : 16 Mar, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads