Tuesday, November 19, 2024
Google search engine
HomeLanguagesJavascriptClasses in TypeScript

Classes in TypeScript

Class in term of OOPs is a blueprint for creating objects. TypeScript supports object-oriented programming features like classes, Interfaces, Polymorphism, data-binding etc. Object means this a real world entity. JavaScript ES5 or earlier didn’t support classes. Typescript inherits this feature from ES6.

In class group of objects which have common properties. Class contains fields, methods, constructors, Blocks, Nested
class and interface.

Syntax to declare a class:

class class_Name{    
    field;    
    method;    
}  

Here, in place of class_Name, name will be there, and inside field and method or function.
If we compile this, It will generate JavaScript code.

// Generated by typescript 1.8.10
var Person = (function () {
   function Person() {
   }
   return Person;
}());

We will see a simple example:

class Person {
perCode: number;
perName: string;

constructor(code: number, name: string) {
this.perName = name;
this.perCode = code;
}

getGrade() : string {
return “A+” ;
}
}

The example declare a Student class which has two fields that is perCode and perName and a constructor which is special type of function which is responsible for variable or object initialization. Here is parameterized constructor. And this keyword which refers to the current instance of the class.
getGrade() is a simple function.
The TypeScript compiler will convert the above class in JavaScript code:
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.
The syntax is given below ?

var object_name = {
   // scalar value 
   key1: “value”, 

   // functions
   key2: function() { 
   }, 

   // collection  
   key3:[“content1”, “content2”] 
};

An objects can contain scalar value, functions and structures like arrays and tuples.
We can represent object in literal notation:

var person = {
fName:”Marry”,
lName:”Jerry”
};

// Access the object values
console.log(person.fName)
console.log(person.lName)

Marry
Jerry

Let’s see with simple example:

var person = {
fName:”Vivek”,
lName:”Hanks”,

// Type template
Hello:function() { }
}

person.Hello = function() {
console.log(“hello “+person.fName)
}

person.Hello()

Output:

hello Vivek

Objects as function parameters

var person = {
fname:”Vivek”,
lname:”Ranjan”
};
var hello = function(obj: { fname:string, lname:string }) {
console.log(“first name :”+obj.fname)
console.log(“last name :”+obj.lname)
}
hello(person)

Output:

first name :Vivek
last name :Ranjan

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. Memory allocation for all objects in heap memory area. given below:

var object_name = new class_name([ arguments ])

see with simple example declaration:

// Creating an object or instance     
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 we access the data members of a class.

// Accessing an attribute 
obj.field_name 

// Accessing a function 
obj.function_name()

We will see with the example:

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(“neveropen”)

// Access the field
console.log(“Reading attribute value Engine as: ”
+ o1.engine)

// Access the function
o1.disp()

After compilation this will convert into JavaScript code look like:
//Generated by typescript 1.8.10

var Car = (function () {
// Here is constructor
function Car(engine) {
this.engine = engine;
}

// Function working
Car.prototype.display = function () {
console.log(“Function displays Engine is: ”
+ this.engine);
};
return Car;
}());

// Create an object
var o1 = new Car(“geks”);

// Access the field value
console.log(“Attribute value Engine as: ”
+ o1.engine);

// Access the display function
o1.display();

Output:

Attribute value Engine as :  neveropen
Function displays Engine is : neveropen
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Previous article
Next article
RELATED ARTICLES

Most Popular

Recent Comments