TypeScript Class vs Interface Explained with Examples

TypeScript, a superset of JavaScript, enhances the language with static types, making it a powerful tool for building large-scale applications. Two fundamental concepts in TypeScript are classes and interfaces. Understanding when and how to use them is crucial for writing clean, maintainable code.

In this tutorial, we will understand the TypeScript class vs interface, explain their use cases with examples, and provide examples to illustrate their applications.

Table of Contents

  1. Introduction
  2. What is a Class?
  3. What is an Interface?
  4. Key Differences Between Classes and Interfaces
  5. When to Use Classes
  6. When to Use Interfaces
  7. Examples
  8. Summary
  9. Conclusion

Introduction to Class and Interface in TypeScript

Classes and interfaces are two core features of TypeScript that help define objects’ structure and behavior. While they may seem similar, they serve different purposes and are used in different scenarios. This guide will help you understand these differences and make informed decisions in your TypeScript projects.

What is a Class in TypeScript?

A class in TypeScript is a blueprint for creating objects with specific properties and methods. It encapsulates data and functions that operate on that data, promoting the object-oriented programming (OOP) paradigm.

Example of a Class

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.`);
    }
}

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

In this example, the Person class has two properties (name and age) and a method (greet). The constructor initializes the properties, and the method provides functionality.

TypeScript Class vs Interface Explained with Examples

Check out: Extend Interfaces with Classes in TypeScript

What is an Interface in TypeScript?

An interface in TypeScript defines an object’s shape. It is a virtual structure that acts as a contract in your code, ensuring that any object adhering to the interface has specific properties and methods.

Example of an Interface

interface Person {
    name: string;
    age: number;
    greet(): void;
}

const person: Person = {
    name: "Jane Doe",
    age: 25,
    greet() {
        console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
    }
};

person.greet(); // Output: Hello, my name is Jane Doe and I am 25 years old.

In this example, the Person interface defines the structure of any object. The object person adheres to this structure, ensuring type safety.

What is an Interface in TypeScript

Check out: Choose Between TypeScript Classes and Interfaces

Key Differences Between TypeScript Class vs Interface

FeatureClassInterface
DefinitionBlueprint for creating objectsContract for object structure
PropertiesCan contain properties and methodsCan only define property and method signatures
InstantiationCan be instantiatedCannot be instantiated
ImplementationCan implement interfacesCannot implement classes
InheritanceCan extend other classesCan extend other interfaces
UsageUsed for creating instances with behaviorUsed for type-checking and ensuring object structure

When to Use Classes in TypeScript?

Classes are ideal when you must create objects with data and behavior. They are particularly useful in the following scenarios:

  1. Encapsulation: When you need to encapsulate data and methods that operate on that data.
  2. Inheritance: When you need to create a hierarchy of objects that share common behavior.
  3. Object Creation: When you need to create multiple instances of an object with shared properties and methods.

Example: Using Classes for Inheritance in TypeScript

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.`);
    }
}

const dog = new Dog("Buddy");
dog.makeSound(); // Output: Buddy barks.

In this example, the Dog class inherits from the Animal class, demonstrating the use of inheritance to share common behavior.

Use Classes for Inheritance in TypeScript

When to Use Interfaces in TypeScript?

Interfaces are best used when you need to define the structure of an object without implementing behavior. They are useful in the following scenarios:

  1. Type Checking: When you need to ensure that objects adhere to a specific structure.
  2. Loose Coupling: When you want to decouple the definition of an object from its implementation.
  3. API Definitions: When defining the shape of data returned from APIs.

Example: Using Interfaces for Type Checking in TypeScript

interface Vehicle {
    make: string;
    model: string;
    year: number;
}

function printVehicle(vehicle: Vehicle) {
    console.log(`${vehicle.make} ${vehicle.model} (${vehicle.year})`);
}

const myCar = {
    make: "Toyota",
    model: "Camry",
    year: 2020
};

printVehicle(myCar); // Output: Toyota Camry (2020)

In this example, the Vehicle interface ensures that the myCar object has the required properties.

When to Use Interfaces in TypeScript

Summary

FeatureClassInterface
DefinitionBlueprint for creating objectsContract for object structure
PropertiesCan contain properties and methodsCan only define properties and methods signatures
InstantiationCan be instantiatedCannot be instantiated
ImplementationCan implement interfacesCannot implement classes
InheritanceCan extend other classesCan extend other interfaces
UsageUsed for creating instances with behaviorUsed for type-checking and ensuring object structure

Conclusion

Understanding the differences between classes and interfaces in TypeScript is essential for writing robust, maintainable code. Classes are ideal for creating objects with both data and behavior, supporting encapsulation and inheritance. Interfaces, on the other hand, are perfect for defining the structure of objects and ensuring type safety through type checking.

By leveraging the strengths of both classes and interfaces, you can create well-structured and efficient TypeScript applications. Whether you are building complex systems or simple applications, knowing when to use each will help you write cleaner and more maintainable code.

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.