Reusable Types

Lesson 6: Interfaces and Type Aliases

Reduce repeated code and create reusable structures by using interfaces and type aliases for objects, unions, and more flexible definitions.

Interfaces

An interface describes the shape of an object and allows you to reuse the same definition in multiple places.

interface Student {
  name: string;
  age: number;
  grade: string;
}
let student1: Student = {
  name: "Ali",
  age: 20,
  grade: "A"
};

Optional and Readonly Properties

interface User {
  name: string;
  email?: string;
  readonly id: number;
}

Type Aliases

Type aliases can also name object structures, but they are especially useful for unions and tuples.

type Status = "Open" | "Closed" | "Pending";
type Point = [number, number];

When to Use Each

  • Use interface mainly for object structures.
  • Use type for unions, tuples, and combined types.
Tip: Both interfaces and type aliases improve readability and reduce duplication, especially as projects grow.

Summary

Interfaces and type aliases help you organize data structures in a reusable way. They are essential tools for clean and scalable TypeScript code.