Interface vs Type in TypeScript: A Detailed Comparison

Interface vs Type in TypeScript: A Detailed Comparison

ยท

4 min read

Introduction

  • TypeScript, a statically typed superset of JavaScript, provides developers with robust tools to define the shapes and structures of objects.

  • Two of the most commonly used tools are Interfaces and Types.

  • While they might seem similar at first glance, there are distinct differences and specific use cases for each.

  • In this blog, we will explore the differences between Interfaces and Types in TypeScript, their unique features, and when to use which. Let's dive in!

What are Interfaces?

  • Interfaces in TypeScript define the structure of an object. T

  • hey are used to describe the shape of an object, specifying what properties and methods it should have.

  • Interfaces enforce a contract within your code, ensuring that objects adhere to a specific structure.

      interface User {
          id: number;
          name: string;
          email: string;
          isActive: boolean;
      }
    

What are Types?

  • Types in TypeScript are more flexible.

  • They can be used to define primitive types, object types, union types, and more.

Types can describe any valid JavaScript value and are often used to create complex type aliases.

type User = {
    id: number;
    name: string;
    email: string;
    isActive: boolean;
};

Key Differences

InterfacesTypes
Extending & MergingInterfaces can be extended using the extends keyword, and they can be merged. This means you can define the same interface in multiple declarations and TypeScript will merge them into a single interface.Types can be extended using intersection types (&), but they cannot be merged. Each type alias declaration is distinct.
Usage with Primitives and Complex TypesInterfaces are primarily used to define object shapes and cannot directly represent union types and tuples.Types are more versatile. They can represent primitive types, union types, tuples, and more.
Declaration ContextInterfaces are best suited for defining the structure of objects, especially when those structures need to be extended or implemented by classes.Types are ideal for more complex type definitions and unions.
interface User {
    id: number;
    name: string;
}

interface User {
    email: string;
    isActive: boolean;
}

// Merged Interface
const user: User = {
    id: 1,
    name: "John Doe",
    email: "john.doe@example.com",
    isActive: true
};
type User = {
    id: number;
    name: string;
};

type UserDetails = User & {
    email: string;
    isActive: boolean;
};

const user: UserDetails = {
    id: 1,
    name: "John Doe",
    email: "john.doe@example.com",
    isActive: true
};

Real Life Example: API Response

Consider an API that returns user data along with status information. We'll use both Interfaces and Types to define these structures.

interface User {
    id: number;
    name: string;
    email: string;
    isActive: boolean;
}

interface ApiResponse {
    status: string;
    data: User[];
}

function fetchUsers(): ApiResponse {
    return {
        status: "success",
        data: [
            { id: 1, name: "John Doe", email: "john.doe@example.com", isActive: true },
            { id: 2, name: "Jane Doe", email: "jane.doe@example.com", isActive: false }
        ]
    };
}

const response = fetchUsers();
console.log(response);

Using Types

type User = {
    id: number;
    name: string;
    email: string;
    isActive: boolean;
};

type ApiResponse = {
    status: string;
    data: User[];
};

function fetchUsers(): ApiResponse {
    return {
        status: "success",
        data: [
            { id: 1, name: "John Doe", email: "john.doe@example.com", isActive: true },
            { id: 2, name: "Jane Doe", email: "jane.doe@example.com", isActive: false }
        ]
    };
}

const response = fetchUsers();
console.log(response);

Conclusion

  • Interfaces and Types in TypeScript both serve the purpose of defining the shape of data, but they come with their own strengths and use cases.

  • Interfaces are ideal for defining the structure of objects and are highly extendable and mergeable.

  • Types, on the other hand, offer greater flexibility and are suitable for complex type definitions.

  • Understanding the differences and knowing when to use each can significantly improve the readability, maintainability, and robustness of your TypeScript code.

Thank You Everyone For The Read ....

Happy Coding! ๐Ÿคž๐Ÿ’ป


๐Ÿ‘‹ Hello, I'm Aaryan Bajaj .

๐Ÿฅฐ If you liked this article, consider sharing it.

๐Ÿ”— X | LinkedIn

ย