Why to Choose Types Instead of Interfaces

Shagun Bidawatka - Aug 5 - - Dev Community

In TypeScript, both Types and Interfaces are used to define the types of objects. However, they have different uses and features. Both can help developers constrain the types of variables and objects when writing code, thereby reducing errors and improving code readability.

So why Types? Let's discuss this.

Types

In TypeScript, a type lets you define the shape of data. It’s flexible and can be used to create unions, intersections, and more.

type User = {
  name: string;
  age: number;
};

type Admin = User & {
  isAdmin: boolean;
};
Enter fullscreen mode Exit fullscreen mode

Interfaces

An interface is another way to define the shape of an object. It’s more rigid than types and is mainly used for defining object shapes and class contracts.

interface User {
  name: string;
  age: number;
}

interface Admin extends User {
  isAdmin: boolean;
}
Enter fullscreen mode Exit fullscreen mode

Why I Prefer Types

  • Union

Union types let you define a type that can be one of several types. This is handy for function parameters and return types. Here, ID can be either a string or a number, demonstrating the power of union types.

type ID = string | number;

function getUserId(id: ID): string {
  return `User ID: ${id}`;
}
Enter fullscreen mode Exit fullscreen mode
  • String Literals

Literal types let you specify exact values a variable can have. This can be really useful for defining constants or configuration options.

type Direction = 'north' | 'south' | 'east' | 'west';

function move(direction: Direction) {
  console.log(`Moving ${direction}`);
}

move('north');
Enter fullscreen mode Exit fullscreen mode
  • Conditional types

Types allow the creation of conditional types, enabling the selection of types based on conditions

type Check<T> = T extends string ? string : number;

let result1: Check<string>; // result1 is of type string
let result2: Check<number>; // result2 is of type number
Enter fullscreen mode Exit fullscreen mode
  • Intersection

Intersection types allow you to combine multiple types into one. This is especially useful for creating complex type compositions.

type Person = {
  name: string;
  age: number;
};

type Employee = {
  employeeId: number;
};

type EmployeeDetails = Person & Employee;

const employee: EmployeeDetails = {
  name: 'Dev',
  age: 30,
  employeeId: 12345,
};
Enter fullscreen mode Exit fullscreen mode

Choosing between types and interfaces ultimately depends on your specific use case and personal preference. However, understanding the strengths of each can help you make more informed decisions and write better TypeScript code.

. . . . . . . .
Terabox Video Player