Lesson 47 of 60 – Classes
78%

Classes in TypeScript

Classes in TypeScript are blueprints for creating objects. They allow you to combine data and functions into a single structure. TypeScript adds static typing to JavaScript classes, making them easier to develop and maintain.

Note: Classes are an important part of object-oriented programming and are commonly used when building larger TypeScript, React, and React Native applications.

1. What is a Class?

A class is a blueprint used to create objects.

class Student {

    name: string;

}

const student =
    new Student();

student.name = "Amit";

console.log(student.name);

The Student class defines the structure of a student object.

2. Why Use Classes?

Classes are useful for organizing related data and behavior.

class Student {

    name: string;

    study(): void {

        console.log(
            this.name + " is studying"
        );

    }

}

A class can contain both properties and methods.

3. Creating a Class

Use the class keyword followed by the class name.

class Car {

    brand: string;

}

The class can later be used to create objects.

4. Creating an Object from a Class

Use the new keyword to create an object.

class Car {

    brand: string;

}

const car =
    new Car();

car.brand = "Toyota";

console.log(car.brand);

5. Class Properties

Properties store data inside an object created from a class.

class Student {

    name: string;
    age: number;
    course: string;

}

const student =
    new Student();

student.name = "Amit";
student.age = 20;
student.course = "TypeScript";

6. Class Methods

Methods are functions defined inside a class.

class Student {

    name: string = "Amit";

    study(): void {

        console.log(
            this.name + " is studying"
        );

    }

}

const student =
    new Student();

student.study();

7. The this Keyword

The this keyword refers to the current object.

class Student {

    name: string;

    showName(): void {

        console.log(
            this.name
        );

    }

}

const student =
    new Student();

student.name = "Rahul";

student.showName();

8. Class with Constructor

A constructor is a special method that runs automatically when an object is created.

class Student {

    name: string;

    constructor(name: string) {

        this.name = name;

    }

}

const student =
    new Student("Amit");

console.log(student.name);

9. Constructor with Multiple Properties

class Student {

    name: string;
    age: number;

    constructor(
        name: string,
        age: number
    ) {

        this.name = name;
        this.age = age;

    }

}

const student =
    new Student(
        "Amit",
        20
    );

console.log(student);

10. Class Method with Parameters

class Calculator {

    add(
        a: number,
        b: number
    ): number {

        return a + b;

    }

}

const calculator =
    new Calculator();

console.log(
    calculator.add(10, 20)
);

11. Class Method with Return Type

class Calculator {

    multiply(
        a: number,
        b: number
    ): number {

        return a * b;

    }

}

The return type of the method is specified after the parameter list.

12. Multiple Objects from One Class

One class can be used to create many objects.

class Student {

    constructor(
        public name: string
    ) {}

}

const student1 =
    new Student("Amit");

const student2 =
    new Student("Rahul");

const student3 =
    new Student("Neha");

console.log(student1.name);
console.log(student2.name);
console.log(student3.name);

13. Class Property Initialization

A class property can have an initial value.

class Student {

    name: string = "Unknown";
    age: number = 0;
    course: string = "Not Assigned";

}

const student =
    new Student();

console.log(student);

14. Optional Class Properties

A property can be optional by using ?.

class Student {

    name: string;
    phone?: string;

    constructor(name: string) {

        this.name = name;

    }

}

const student =
    new Student("Amit");

console.log(student.name);

15. Class with a Boolean Property

class Student {

    name: string;
    active: boolean;

    constructor(
        name: string,
        active: boolean
    ) {

        this.name = name;
        this.active = active;

    }

    showStatus(): void {

        if (this.active) {

            console.log(
                this.name +
                " is active"
            );

        } else {

            console.log(
                this.name +
                " is inactive"
            );

        }

    }

}

const student =
    new Student(
        "Amit",
        true
    );

student.showStatus();

16. Class with an Array Property

class Student {

    subjects: string[];

    constructor(
        subjects: string[]
    ) {

        this.subjects = subjects;

    }

    showSubjects(): void {

        console.log(
            this.subjects
        );

    }

}

const student =
    new Student([
        "HTML",
        "CSS",
        "TypeScript"
    ]);

student.showSubjects();

17. Class with Multiple Methods

class Calculator {

    add(
        a: number,
        b: number
    ): number {

        return a + b;

    }

    subtract(
        a: number,
        b: number
    ): number {

        return a - b;

    }

    multiply(
        a: number,
        b: number
    ): number {

        return a * b;

    }

}

const calculator =
    new Calculator();

console.log(
    calculator.add(10, 5)
);

console.log(
    calculator.subtract(10, 5)
);

console.log(
    calculator.multiply(10, 5)
);

18. Class with Getter Method

A getter allows you to access a calculated value like a property.

class Student {

    constructor(
        public name: string,
        public age: number
    ) {}

    get details(): string {

        return this.name +
            " - " +
            this.age;

    }

}

const student =
    new Student(
        "Amit",
        20
    );

console.log(
    student.details
);

19. Class with Setter Method

A setter allows you to control how a property is changed.

class Student {

    private _name: string = "";

    get name(): string {

        return this._name;

    }

    set name(
        value: string
    ) {

        this._name = value;

    }

}

const student =
    new Student();

student.name = "Amit";

console.log(
    student.name
);

20. Class with Static Property

A static property belongs to the class itself rather than individual objects.

class Student {

    static schoolName =
        "Soopro Pathshala";

}

console.log(
    Student.schoolName
);

21. Class Implements Interface

A class can implement an interface and must follow its required structure.

interface Person {

    name: string;

    showName(): void;

}

class Student
    implements Person {

    constructor(
        public name: string
    ) {}

    showName(): void {

        console.log(
            this.name
        );

    }

}

const student =
    new Student("Amit");

student.showName();

22. Generic Class

Classes can also use generic type parameters.

class Box<T> {

    constructor(
        public value: T
    ) {}

    getValue(): T {

        return this.value;

    }

}

const numberBox =
    new Box<number>(100);

const stringBox =
    new Box<string>("Hello");

console.log(
    numberBox.getValue()
);

console.log(
    stringBox.getValue()
);

23. Abstract Class Introduction

An abstract class is a base class that is designed to be extended by other classes.

abstract class Animal {

    abstract makeSound(): void;

    move(): void {

        console.log(
            "Animal is moving"
        );

    }

}

Abstract classes cannot be directly instantiated.

24. Class Inheritance Preview

One class can extend another class using the extends keyword.

class Animal {

    move(): void {

        console.log(
            "Animal is moving"
        );

    }

}

class Dog extends Animal {

    bark(): void {

        console.log(
            "Dog is barking"
        );

    }

}

const dog =
    new Dog();

dog.move();
dog.bark();

Inheritance will be covered in more detail in a later lesson.

25. Classes in React Applications

Modern React applications commonly use functional components, but TypeScript classes are still useful for modeling data, services, and business logic.

class UserService {

    getUserName(
        name: string
    ): string {

        return name;

    }

}

const service =
    new UserService();

console.log(
    service.getUserName("Amit")
);

26. Classes in React Native

In React Native, classes can be used for reusable services, models, storage helpers, API managers, and other application logic.

class UserService {

    getUser(
        id: number
    ): string {

        return "User " + id;

    }

}

const service =
    new UserService();

const user =
    service.getUser(101);

console.log(user);

27. Common Class Mistakes

  • Forgetting to use new when creating an object.
  • Using a property without declaring or initializing it properly.
  • Forgetting to assign constructor parameters to properties.
  • Using the wrong property or method type.
  • Accessing private members from outside the class.
  • Creating unnecessarily complex classes.

28. Class Best Practices

  • Use meaningful class names.
  • Keep each class focused on a clear responsibility.
  • Use explicit property and method types.
  • Use constructors to initialize required data.
  • Use access modifiers when appropriate.
  • Use interfaces when a class needs to follow a structure.
  • Use generics when a class needs to work with different types.

29. Complete Practical Example

interface StudentData {

    id: number;
    name: string;
    course: string;

}

class Student {

    private data: StudentData;

    constructor(
        data: StudentData
    ) {

        this.data = data;

    }

    getName(): string {

        return this.data.name;

    }

    getCourse(): string {

        return this.data.course;

    }

    showDetails(): void {

        console.log(
            "ID:",
            this.data.id
        );

        console.log(
            "Name:",
            this.data.name
        );

        console.log(
            "Course:",
            this.data.course
        );

    }

}

const student =
    new Student({

        id: 101,
        name: "Amit",
        course: "TypeScript"

    });

student.showDetails();

console.log(
    student.getName()
);

console.log(
    student.getCourse()
);

This example combines an interface, class, constructor, private property, and class methods.

30. Classes Summary

Classes provide a structured way to create objects and organize data and behavior in TypeScript.

class Student {

    constructor(
        public name: string,
        public course: string
    ) {}

    showDetails(): void {

        console.log(
            this.name +
            " - " +
            this.course
        );

    }

}

const student =
    new Student(
        "Amit",
        "TypeScript"
    );

student.showDetails();

Classes become especially useful when combined with interfaces, inheritance, access modifiers, generics, and other object-oriented programming features.

📌 Key Points

  • A class is a blueprint for creating objects.
  • Use the class keyword to create a class.
  • Use new to create an object from a class.
  • Classes can contain properties.
  • Classes can contain methods.
  • The this keyword refers to the current object.
  • Constructors initialize objects when they are created.
  • Classes can contain optional properties.
  • Classes can contain arrays and other data types.
  • Getters and setters control property access.
  • Classes can contain static members.
  • Classes can implement interfaces.
  • Classes can use generic type parameters.
  • Classes can participate in inheritance and abstraction.
  • Classes can be useful for services and models in React Native applications.

🧠 Quick Quiz

Question: Which keyword is used to create an object from a TypeScript class?