Lesson 2 of 3

Types and Interfaces

Learn how to define custom types and interfaces to create robust, self-documenting code structures.

25 minutes

Types and Interfaces

Types and interfaces are the foundation of TypeScript's type system.

Type Aliases

Create custom types using the type keyword:

type Status = "pending" | "approved" | "rejected";
type ID = string | number;

Interfaces

Interfaces define the shape of objects:

  • Define required and optional properties
  • Support extending other interfaces
  • Can be implemented by classes

When to Use Each

  • Types: Union types, primitives, tuples
  • Interfaces: Object shapes, class contracts, extension

Optional and Readonly Properties

  • Use ? for optional properties
  • Use readonly for immutable properties

Best Practices

  • Prefer interfaces for object definitions
  • Use types for unions and complex type manipulations
  • Always provide descriptive names

Code Example

// Interface definition
interface User {
  id: number;
  name: string;
  email: string;
  role: "admin" | "user" | "guest";
  createdAt?: Date; // Optional property
}

// Type alias for union types
type ApiResponse<T> = {
  data: T;
  success: boolean;
  message?: string;
};

// Using the interface
const newUser: User = {
  id: 1,
  name: "Alex Thompson",
  email: "alex@example.com",
  role: "admin"
};

// Extending interfaces
interface Employee extends User {
  department: string;
  salary: number;
}

function displayUser(user: User): void {
  console.log(`${user.name} (${user.role})`);
}