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 ${this.name} and I am ${this.age} years old.`;
}
}
const person1 = new Person("Alice", 25);
console.log(person1.introduce());
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 Classespublic
: 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.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: ${john.name}, Age: ${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 = {Accessing Attributes and Functions
key1: value1,
key2: value2,
// ...
};
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 attributeSimple Object
obj.field_name or obj['field_name']
//accessing a function
obj.function_name()
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 ${this.name} and I'm ${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 ${this.accountHolder} is $${this.balance}`;
}
}
const account = new BankAccount("John Doe", 500);
account.deposit(200);
console.log(account.getBalance());
Output:
The balance for John Doe is $700Representing 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
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4