Classes and Interfaces in TypeScript

November 4, 2024

Classes and Interfaces in TypeScript

This post introduces object-oriented programming concepts in TypeScript, focusing on classes and interfaces. We will explain how to create and implement them, with usage examples.

Understanding Classes

Classes in TypeScript are a blueprint for creating objects. They encapsulate data for the object and methods to manipulate that data. This is a fundamental concept in object-oriented programming (OOP).

Creating a Class

To create a class in TypeScript, you use the class keyword followed by the class name and the class body. Here’s a simple example:

class Animal {
    name: string;

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

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

Instantiating a Class

Once you have defined a class, you can create an instance of that class using the new keyword:

const dog = new Animal('Dog');

dog.makeSound(); // Output: Dog makes a sound.

Understanding Interfaces

Interfaces in TypeScript are used to define the shape of an object. They specify what properties and methods an object should have without providing the implementation. This is particularly useful for ensuring that certain classes adhere to a specific contract.

Creating an Interface

To create an interface, you use the interface keyword followed by the interface name and its properties:

interface Animal {
    name: string;
    makeSound(): void;
}

Implementing an Interface

Classes can implement interfaces using the implements keyword. This ensures that the class adheres to the structure defined by the interface:

class Dog implements Animal {
    name: string;

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

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

Using Interfaces for Function Parameters

Interfaces can also be useful for defining the types of function parameters. This allows you to enforce that the arguments passed to a function conform to a specific structure:

function makeAnimalSound(animal: Animal): void {
    animal.makeSound();
}

const myDog = new Dog('Buddy');
makeAnimalSound(myDog); // Output: Buddy barks.

Conclusion

In this post, we explored the basics of classes and interfaces in TypeScript. We learned how to create classes, instantiate them, and implement interfaces to define object shapes. Understanding these concepts is essential for leveraging TypeScript’s capabilities in object-oriented programming.

In the next post, we will dive deeper into inheritance and polymorphism in TypeScript, so stay tuned!