DEV Community

Cover image for Mastering Object-Oriented Programming with TypeScript: A Beginner's Guide
Jakaria Masum
Jakaria Masum

Posted on

Mastering Object-Oriented Programming with TypeScript: A Beginner's Guide

Object-oriented programming (OOP) is a powerful paradigm that allows developers to create modular, reusable, and maintainable code. TypeScript, with its robust type system and modern JavaScript features, provides excellent support for OOP principles. In this guide, we'll explore the key concepts of object-oriented TypeScript, including classes, interfaces, inheritance, access modifiers, abstract classes, and more.

1. Classes

Classes are the cornerstone of OOP in TypeScript. They provide a blueprint for creating objects with specific properties and methods.

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 am ${this.age} years old.`);
    }
}

let john = new Person("John Doe", 30);
john.greet(); // Output: Hello, my name is John Doe and I am 30 years old.
Enter fullscreen mode Exit fullscreen mode
  • Constructor: The constructor method is a special method for creating and initializing objects created with a class.
  • Methods: Functions that belong to a class. Here, greet is a method of the Person class.

2. Interfaces

Interfaces define the structure of an object. They are a powerful way to define contracts within your code.

Example:

interface IShape {
    color: string;
    area(): number;
}

class Rectangle implements IShape {
    color: string;
    width: number;
    height: number;

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

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

let myRectangle = new Rectangle("blue", 5, 10);
console.log(myRectangle.area()); // Output: 50
Enter fullscreen mode Exit fullscreen mode
  • Interfaces: Define properties and methods that a class must implement.
  • Implements: The implements keyword ensures that the class follows the structure defined by the interface.

3. Inheritance

Inheritance allows a class to inherit properties and methods from another class, promoting code reuse.

Example:

class Animal {
    name: string;

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

    makeSound() {
        console.log(`${this.name} makes a sound.`);
    }
}

class Dog extends Animal {
    constructor(name: string) {
        super(name);
    }

    makeSound() {
        console.log(`${this.name} barks.`);
    }
}

let myDog = new Dog("Rex");
myDog.makeSound(); // Output: Rex barks.
Enter fullscreen mode Exit fullscreen mode
  • Extends: The extends keyword is used to create a class that is a child of another class.
  • Super: The super keyword is used to call the constructor and methods of the parent class.

4. Access Modifiers

Access modifiers control the visibility of class members. TypeScript supports three access modifiers: public, private, and protected.

Example:

class Car {
    public make: string;
    private model: string;
    protected year: number;

    constructor(make: string, model: string, year: number) {
        this.make = make;
        this.model = model;
        this.year = year;
    }

    public displayMake() {
        console.log(`This car is a ${this.make}.`);
    }

    private displayModel() {
        console.log(`Model: ${this.model}.`);
    }

    protected displayYear() {
        console.log(`Year: ${this.year}.`);
    }
}

let myCar = new Car("Toyota", "Camry", 2020);
myCar.displayMake(); // Output: This car is a Toyota.
// myCar.displayModel(); // Error: Property 'displayModel' is private and only accessible within class 'Car'.
// myCar.displayYear(); // Error: Property 'displayYear' is protected and only accessible within class 'Car' and its subclasses.
Enter fullscreen mode Exit fullscreen mode
  • Public: Accessible from anywhere.
  • Private: Accessible only within the class.
  • Protected: Accessible within the class and its subclasses.

5. Abstract Classes

Abstract classes cannot be instantiated and are meant to be extended by other classes. They can contain abstract methods that must be implemented by subclasses.

Example:

abstract class Animal {
    abstract makeSound(): void; // Abstract method

    move(): void {
        console.log("Moving...");
    }
}

class Cat extends Animal {
    makeSound(): void {
        console.log("Meow");
    }
}

let myCat = new Cat();
myCat.makeSound(); // Output: Meow
myCat.move(); // Output: Moving...
Enter fullscreen mode Exit fullscreen mode
  • Abstract Method: A method that is declared but not implemented in the abstract class. Subclasses must implement this method.

6. Getters and Setters

Getters and setters provide a way to access and update private fields.

Example:

class User {
    private _name: string;

    constructor(name: string) {
        this._name = name;
    }

    get name(): string {
        return this._name;
    }

    set name(newName: string) {
        if (newName.length > 0) {
            this._name = newName;
        } else {
            console.log("Name must be non-empty.");
        }
    }
}

let user = new User("Alice");
console.log(user.name); // Output: Alice
user.name = "Bob";
console.log(user.name); // Output: Bob
user.name = ""; // Output: Name must be non-empty.
Enter fullscreen mode Exit fullscreen mode
  • Get: A getter method to access the value of a private property.
  • Set: A setter method to update the value of a private property.

7. Static Members

Static members (properties and methods) belong to the class itself rather than instances of the class.

Example:

class MathUtil {
    static PI: number = 3.14;

    static circleArea(radius: number): number {
        return this.PI * radius * radius;
    }
}

console.log(MathUtil.PI); // Output: 3.14
console.log(MathUtil.circleArea(5)); // Output: 78.5
Enter fullscreen mode Exit fullscreen mode
  • Static: The static keyword defines a static property or method.

Top comments (0)