TypeScript class (original) (raw)

Last Updated : 23 Jan, 2025

A TypeScript class is a blueprint for creating objects, encapsulating properties (data) and methods (behavior) to promote organization, reusability, and readability.

class Person { name: string; age: number;

constructor(name: string, age: number) { this.name = name; this.age = age; }

introduce(): string { return Hi, my name is <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mrow><mi>t</mi><mi>h</mi><mi>i</mi><mi>s</mi><mi mathvariant="normal">.</mi><mi>n</mi><mi>a</mi><mi>m</mi><mi>e</mi></mrow><mi>a</mi><mi>n</mi><mi>d</mi><mi>I</mi><mi>a</mi><mi>m</mi></mrow><annotation encoding="application/x-tex">{this.name} and I am </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord"><span class="mord mathnormal">t</span><span class="mord mathnormal">hi</span><span class="mord mathnormal">s</span><span class="mord">.</span><span class="mord mathnormal">nam</span><span class="mord mathnormal">e</span></span><span class="mord mathnormal">an</span><span class="mord mathnormal">d</span><span class="mord mathnormal" style="margin-right:0.07847em;">I</span><span class="mord mathnormal">am</span></span></span></span>{this.age} years old.; } }

const person1 = new Person("Alice", 25); console.log(person1.introduce());

``

Output:

Hi, my name is Alice and I am 25 years old.

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

Access Modifiers (public, private, and protected)

Constructors in TypeScript

A **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.

javascript ``

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

const john = new Person('Uday', 20); console.log(Name: <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mrow><mi>j</mi><mi>o</mi><mi>h</mi><mi>n</mi><mi mathvariant="normal">.</mi><mi>n</mi><mi>a</mi><mi>m</mi><mi>e</mi></mrow><mo separator="true">,</mo><mi>A</mi><mi>g</mi><mi>e</mi><mo>:</mo></mrow><annotation encoding="application/x-tex">{john.name}, Age: </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord"><span class="mord mathnormal" style="margin-right:0.05724em;">j</span><span class="mord mathnormal">o</span><span class="mord mathnormal">hn</span><span class="mord">.</span><span class="mord mathnormal">nam</span><span class="mord mathnormal">e</span></span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal">A</span><span class="mord mathnormal" style="margin-right:0.03588em;">g</span><span class="mord mathnormal">e</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">:</span></span></span></span>{john.age});

``

**Output:

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

**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

 let obj = {
key1: value1,
key2: value2,
// ...
};

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()

Simple Object

The Person class has name and age properties set through its constructor. It includes a greet method to log a greeting with these details. Instances like person can **access attributes and methods defined within the class.

JavaScript ``

class Person { name: string; age: number;

constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
}

greet() {
    console.log(`Hello, I'm <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mrow><mi>t</mi><mi>h</mi><mi>i</mi><mi>s</mi><mi mathvariant="normal">.</mi><mi>n</mi><mi>a</mi><mi>m</mi><mi>e</mi></mrow><mi>a</mi><mi>n</mi><mi>d</mi><msup><mi>I</mi><mo mathvariant="normal" lspace="0em" rspace="0em">′</mo></msup><mi>m</mi></mrow><annotation encoding="application/x-tex">{this.name} and I&#x27;m </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.7519em;"></span><span class="mord"><span class="mord mathnormal">t</span><span class="mord mathnormal">hi</span><span class="mord mathnormal">s</span><span class="mord">.</span><span class="mord mathnormal">nam</span><span class="mord mathnormal">e</span></span><span class="mord mathnormal">an</span><span class="mord mathnormal">d</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.07847em;">I</span><span class="msupsub"><span class="vlist-t"><span class="vlist-r"><span class="vlist" style="height:0.7519em;"><span style="top:-3.063em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">′</span></span></span></span></span></span></span></span></span><span class="mord mathnormal">m</span></span></span></span>{this.age} years old.`);
}

}

const person = new Person('Rahul', 22); console.log(person.name); // Accessing attribute person.greet(); // Accessing function

``

**Output:

Rahul
Hello, I'm Rahul and I'm 22 years old.

**More Example of TypeScript Classes

Managing a Bank Account

javascript ``

class BankAccount { accountHolder: string; balance: number;

constructor(accountHolder: string, initialBalance: number) { this.accountHolder = accountHolder; this.balance = initialBalance; }

deposit(amount: number): void { this.balance += amount; }

getBalance(): string { return The balance for <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mrow><mi>t</mi><mi>h</mi><mi>i</mi><mi>s</mi><mi mathvariant="normal">.</mi><mi>a</mi><mi>c</mi><mi>c</mi><mi>o</mi><mi>u</mi><mi>n</mi><mi>t</mi><mi>H</mi><mi>o</mi><mi>l</mi><mi>d</mi><mi>e</mi><mi>r</mi></mrow><mi>i</mi><mi>s</mi></mrow><annotation encoding="application/x-tex">{this.accountHolder} is </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord"><span class="mord mathnormal">t</span><span class="mord mathnormal">hi</span><span class="mord mathnormal">s</span><span class="mord">.</span><span class="mord mathnormal">a</span><span class="mord mathnormal">cco</span><span class="mord mathnormal">u</span><span class="mord mathnormal">n</span><span class="mord mathnormal">t</span><span class="mord mathnormal">Ho</span><span class="mord mathnormal" style="margin-right:0.01968em;">l</span><span class="mord mathnormal">d</span><span class="mord mathnormal" style="margin-right:0.02778em;">er</span></span><span class="mord mathnormal">i</span><span class="mord mathnormal">s</span></span></span></span>${this.balance}; } }

const account = new BankAccount("John Doe", 500); account.deposit(200); console.log(account.getBalance());

``

**Output:

The balance for John Doe is $700

Representing a Rectangle

JavaScript ``

class Rectangle { width: number; height: number;

constructor(width: number, height: number) { this.width = width; this.height = height; }

calculateArea(): number { return this.width * this.height; } }

const rect = new Rectangle(10, 5); console.log(Area of the rectangle: ${rect.calculateArea()});

``

**Ouptut:

Area of the rectangle: 50