Before we reorganise our routes, let’s first move the TypeScript interfaces out of index.ts. Currently, the index file contains interface definitions mixed with server code, which makes both harder to maintain.

Creating a Shared Interfaces File

Create src/interfaces.ts:

export interface User {
  id: number;
  username: string;
  email: string;
}

export interface Post {
  id: number;
  title: string;
  content: string;
  user_id: number;
  created_at: Date;
}

export interface PostWithUser extends Post {
  username: string;
  email: string;
}

What’s happening here

  • Export each interface: Using export makes them available to other files.
  • Single source of truth: All data structures are defined in one place.
  • Clean separation: Interfaces separated from business logic.

Types vs Interfaces

Many TypeScript projects use type instead of interface for data structures:

// Using types instead
export type User = {
  id: number;
  username: string;
  email: string;
};

export type Post = {
  id: number;
  title: string;
  content: string;
  user_id: number;
  created_at: Date;
};

export type PostWithUser = Post & {
  username: string;
  email: string;
};

Key differences

  • Extension syntax: Interfaces use extends, types use intersection (&) for combining types.
  • Naming convention: Projects using types typically have a types.ts file instead of interfaces.ts (or a types folder instead of an interfaces folder.).
  • Both are common: You’ll see both approaches used in different projects.


Repo link

Tags: