How to Choose Between TypeScript Classes and Interfaces?

Someone in a live webinar asked about TypeScript Classes vs Interfaces, when to use which one. In this tutorial, I will explain the differences between TypeScript classes and interfaces, providing detailed examples.

What is a TypeScript Interface?

An interface in TypeScript is a syntactical contract that an entity should conform to. It defines the shape of an object, meaning which properties and methods it should have. Interfaces are purely for type-checking and do not translate to JavaScript code. This makes them lightweight and ideal for defining the structure of objects.

Example of an Interface

Consider an example where we define an interface for a Person object:

interface Person {
    firstName: string;
    lastName: string;
    age: number;
    greet: () => string;
}

const johnDoe: Person = {
    firstName: "John",
    lastName: "Doe",
    age: 30,
    greet: () => `Hello, my name is John Doe`
};

console.log(johnDoe.greet());

In this example, the Person interface ensures that any object adhering to it will have firstName, lastName, age, and greet properties.

Check out Convert JSON to TypeScript Interface

What is a TypeScript Class?

A class in TypeScript is a blueprint for creating objects with pre-defined properties and methods. Unlike interfaces, classes can have actual implementations, including constructors, methods, and properties. Classes are translated into JavaScript code, which means they can be instantiated and used at runtime.

Example of a Class

Here’s how you can define a class for the same Person object:

class Person {
    firstName: string;
    lastName: string;
    age: number;

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

    greet(): string {
        return `Hello, my name is ${this.firstName} ${this.lastName}`;
    }
}

const janeDoe = new Person("Jane", "Doe", 28);
console.log(janeDoe.greet());

In this example, the Person class not only defines the structure of a person but also includes a constructor to initialize new instances and a method to greet.

Read Set Default Values in TypeScript Interfaces

Key Differences Between TypeScript Interfaces and Classes

Now, let me explain a few key differences between TypeScript interfaces and classes.

Purpose and Usage

  • Interfaces are used to define the shape of an object and are best for type-checking. They are ideal when you need to ensure an object adheres to a specific structure without adding any implementation details.
  • Classes are used to create objects with defined properties and methods. They are best suited for scenarios where you need to create multiple instances of an object with shared behavior and state.

Code Translation

  • Interfaces do not translate to JavaScript code. They are removed during the compilation process, making them lightweight.
  • Classes are translated into JavaScript code. This means they can be instantiated and used at runtime.

Inheritance and Implementation

  • Interfaces can extend other interfaces, allowing you to build complex types by combining simpler ones.
  • Classes can extend other classes and implement interfaces, providing a powerful way to create hierarchical and reusable code structures.

Read Differences Between Type and Interface in TypeScript

When to Use Interfaces vs. Classes in TypeScript

Now, let me explain when to use interface vs classes in TypeScript.

Use Interfaces When:

  • You need to define the shape of an object for type-checking purposes.
  • You want to ensure that certain properties and methods are present in an object without adding implementation details.
  • You are working with external libraries or APIs where you need to define the expected structure of data.

Use Classes When:

  • You need to create instances of objects with shared behavior and state.
  • You want to include implementation details such as constructors and methods.
  • You need to leverage object-oriented programming features like inheritance and polymorphism.

Practical Example: Using Interfaces and Classes Together

In many cases, you might find yourself using both interfaces and classes together. For instance, you can define an interface for the structure and a class for the implementation:

interface Car {
    make: string;
    model: string;
    year: number;
    getCarInfo: () => string;
}

class Tesla implements Car {
    make: string;
    model: string;
    year: number;

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

    getCarInfo(): string {
        return `${this.year} ${this.make} ${this.model}`;
    }
}

const myTesla = new Tesla("Tesla", "Model S", 2022);
console.log(myTesla.getCarInfo());

In this example, the Car interface defines the structure, while the Tesla class provides the implementation.

Read Create an Object from an Interface in TypeScript

TypeScript Classes Vs. Interfaces

Sure! Here’s a summary of the key differences between TypeScript classes and interfaces:

FeatureInterfaceClass
PurposeDefine the shape of an object for type-checkingCreate objects with defined properties and methods
Code TranslationNot translated to JavaScriptTranslated to JavaScript
UsageEnsures object structure without implementationIncludes implementation details like constructors and methods
InheritanceCan extend other interfacesCan extend other classes and implement interfaces
InstancesCannot create instancesCan create instances
LightweightYesNo
Ideal ForType-checking, defining structureCreating objects with shared behavior and state
Exampletypescript |typescript
interface Person {class Person {
firstName: string;firstName: string;
lastName: string;lastName: string;
age: number;age: number;
greet: () => string;constructor(firstName: string, lastName: string, age: number) {
}this.firstName = firstName;
const johnDoe: Person = {this.lastName = lastName;
firstName: “John”,this.age = age;
lastName: “Doe”,}
age: 30,greet(): string {
greet: () => Hello, my name is John Doereturn Hello, my name is ${this.firstName} ${this.lastName};
};}
console.log(johnDoe.greet());}
“`const janeDoe = new Person(“Jane”, “Doe”, 28);
console.log(janeDoe.greet());
“`

This table provides a quick reference to help you decide when to use TypeScript interfaces and when to use classes, based on their features and use cases.

Choose Between TypeScript Classes and Interfaces

Conclusion

In this tutorial, I explained the differences between TypeScript classes and interfaces. And I hope now you understand when to use the interface and when to use classes in TypeScript. Do let me know in the comment if you still have some questions.