Start Coding

Topics

TypeScript Class Basics

Classes in TypeScript provide a powerful way to create reusable, object-oriented code. They encapsulate data and behavior, making it easier to organize and maintain complex applications.

Class Declaration

To declare a class in TypeScript, use the class keyword followed by the class name. Here's a simple example:


class Person {
    name: string;
    age: number;

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

    greet() {
        console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
    }
}
    

Class Properties

Properties are variables declared within a class. They can be typed and initialized in the class body or the constructor. TypeScript supports public, private, and protected access modifiers for properties.

Constructors

The constructor method is called when creating a new instance of a class. It initializes the object's properties. TypeScript allows parameter properties, which automatically create and initialize class members:


class Employee {
    constructor(private id: number, public name: string) {}
}

const emp = new Employee(1, "John Doe");
console.log(emp.name); // Output: John Doe
    

Methods

Methods are functions defined within a class. They can access and modify the class's properties using the this keyword.

Creating and Using Class Instances

To create an instance of a class, use the new keyword followed by the class name and constructor arguments:


const person = new Person("Alice", 30);
person.greet(); // Output: Hello, my name is Alice and I'm 30 years old.
    

Inheritance

TypeScript supports inheritance, allowing classes to extend other classes. Use the extends keyword to create a subclass:


class Student extends Person {
    constructor(name: string, age: number, public studentId: string) {
        super(name, age);
    }
}
    

Best Practices

Classes in TypeScript provide a robust foundation for object-oriented programming. They offer type safety, inheritance, and encapsulation, making it easier to build scalable and maintainable applications.