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
exportmakes 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.tsfile instead ofinterfaces.ts(or atypesfolder instead of aninterfacesfolder.). - Both are common: You’ll see both approaches used in different projects.