Open In App

TypeScript class

Last Updated : 23 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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

  • Supports inheritance, allowing one class to extend another and reuse functionality.
  • Provides access modifiers (public, private, protected) to control member accessibility and enforce encapsulation.
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());
  • The Person class defines properties name and age, a constructor for initialization, and a method introduce to return a greeting message.
  • An object person1 is created from the class, and the introduce method is called to output a personalized message.

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

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

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.

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 = {
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.

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

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());
  • The BankAccount class allows for creating an account, adding deposits, and checking the balance.
  • account.deposit(200) adds $200 to the initial balance of $500, and getBalance displays the updated balance.

Output:

The balance for John Doe is $700

Representing a Rectangle

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()}`);
  • The Rectangle class calculates the area of a rectangle using its width and height.
  • calculateArea() is invoked on the rectangle object to compute the area.

Ouptut:

Area of the rectangle: 50

TypeScript Classes – FAQs

How do you define a class in TypeScript?

Use the class keyword followed by the class name and curly braces containing properties and methods.

What are access modifiers in TypeScript?

Access modifiers (public, private, protected) define the accessibility scope of class members.

How does inheritance work in TypeScript?

Inheritance allows a class to extend another class, inheriting its properties and methods.

What are TypeScript class methods?

Methods are functions defined within a class that perform specific actions.

How do you create an instance of a TypeScript class?

Use the new keyword followed by the class name and any required constructor parameters.

Can TypeScript classes implement interfaces?

Yes, classes can implement interfaces to ensure they adhere to specific structures.



Next Article

Similar Reads

three90RightbarBannerImg