DEV Community

Safal Bhandari
Safal Bhandari

Posted on

Understanding TypeScript Interfaces: A Complete Guide

TypeScript is a powerful superset of JavaScript that brings static typing to your code. One of its most powerful features is interfaces, which allow you to define structured types for objects, functions, and classes. In this article, we’ll explore what interfaces are, how to use them with objects, React components, and classes, and even see how they compare to abstract classes.


What Are Interfaces?

Interfaces in TypeScript allow you to define custom types for objects. Think of them as contracts that your data must adhere to. This ensures type safety and improves code readability.

Consider a simple user object:

const user = {
  firstName: "Harkirat",
  lastName: "Singh",
  email: "email@gmail.com",
  age: 21,
};
Enter fullscreen mode Exit fullscreen mode

To assign a type to this object, you can define an interface:

interface User {
  firstName: string;
  lastName: string;
  email: string;
  age: number;
}
Enter fullscreen mode Exit fullscreen mode

Now, whenever you use a User type in your code, TypeScript will enforce the shape of the object according to this interface.


Assignment 1: Checking Legal Age

Let’s create a function that checks if a user is above 18:

function isLegal(user: User): boolean {
  return user.age > 18;
}

console.log(isLegal(user)); // true
Enter fullscreen mode Exit fullscreen mode

This function uses the User interface to ensure it only accepts valid user objects.


Assignment 2: Using Interfaces in React

Interfaces are also extremely useful in React components, especially when working with props. For example, consider a Todo component:

// Todo.tsx
interface TodoType {
  title: string;
  description: string;
  done: boolean;
}

interface TodoInput {
  todo: TodoType;
}

function Todo({ todo }: TodoInput) {
  return (
    <div>
      <h1>{todo.title}</h1>
      <h2>{todo.description}</h2>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Here, TodoType defines the structure of a todo object, and TodoInput defines the shape of the props that the component expects. This ensures type safety in React components.

💡 Tip: When creating a new React project, you can select TypeScript while initializing with Vite:

npm create vite@latest my-app --template react-ts
Enter fullscreen mode Exit fullscreen mode

Implementing Interfaces in Classes

Interfaces aren’t just for objects; they can also be used as contracts for classes.

Example:

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

class Employee implements Person {
  name: string;
  age: number;

  constructor(n: string, a: number) {
    this.name = n;
    this.age = a;
  }

  greet(phrase: string) {
    console.log(`${phrase} ${this.name}`);
  }
}

const emp = new Employee("Harkirat", 21);
emp.greet("Hello"); // Hello Harkirat
Enter fullscreen mode Exit fullscreen mode

By implementing an interface, a class guarantees that it has all the properties and methods defined in the interface. This makes your code more predictable and maintainable.


Abstract Classes vs Interfaces

TypeScript also provides abstract classes, which are similar to interfaces but can contain implemented methods. Abstract classes allow you to define a blueprint for other classes to follow:

abstract class Shape {
  abstract name: string;

  abstract calculateArea(): number;

  describe(): void {
    console.log(`This shape is a ${this.name} with an area of ${this.calculateArea()} units squared.`);
  }
}

class Rectangle extends Shape {
  name = "Rectangle";

  constructor(public width: number, public height: number) {
    super();
  }

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

class Circle extends Shape {
  name = "Circle";

  constructor(public radius: number) {
    super();
  }

  calculateArea(): number {
    return Math.PI * this.radius * this.radius;
  }
}

const rect = new Rectangle(5, 10);
rect.describe(); // This shape is a Rectangle with an area of 50 units squared.
Enter fullscreen mode Exit fullscreen mode

While interfaces define only the structure, abstract classes allow you to define both structure and behavior, making them slightly more powerful in certain scenarios.


Summary

  • Interfaces define the structure of objects, function parameters, or classes.
  • Use interfaces in React components for type-safe props.
  • Classes can implement interfaces to ensure they follow a specific contract.
  • Abstract classes combine structure and behavior, useful when you want shared methods across multiple classes.

TypeScript interfaces help make your code cleaner, safer, and more maintainable. Whether you’re working with objects, React components, or classes, understanding interfaces is key to mastering TypeScript.


Top comments (0)