Logo

TypeScript

Interfaces

JavaScript is the Wild West: Everything is allowed. Interfaces are the sheriff. They enforce structure on your data and prevent chaos.

Coming from JavaScript, API integrations used to be a minefield. Was the field called userName, username, or user_name? One typo, and the app crashes in production.

Interfaces solve exactly that. They are a contract. If I define: "A user must have an email," the compiler will scream at me if I try to create a user without one.
The best part isn't just safety—it's IntelliSense. I press . and my IDE tells me exactly what data is available. No more guessing.

1. The Simulation

Try to create a valid User object below. The "compiler" on the right monitors live whether your data matches the interface contract.

Object Creation
editor.ts
interfaceUser {
  username: string;
  age: number;
  isPremium?: boolean;
}
const currentUser: User = {
  username: "",
  age: null,
  isPremium: false
};

2. Implementation

Important concept: An interface exists only during development. It helps us while coding. In the final JavaScript bundle, it disappears completely (Zero Runtime Overhead).

Step 1: Set up the contract

I use interfaces not only for data types but also to enforce specific values (Union Types). This prevents me from accidentally writing "Admin" (uppercase) instead of "admin" (lowercase).

user.interface.ts
// 1. Define sub-types first
export interface Address {
  city: string;
  zip: number;
}

// 2. Compose them into the main model
export interface User {
  id: number;
  username: string;
  email: string;

  // Optional field (marked with ?)
  // Use this for data that might be null/undefined
  avatarUrl?: string;

  // Nested Interface
  address: Address;

  // Union Type: strict value enforcement
  // Much safer than just 'string'!
  role: 'admin' | 'editor' | 'viewer';
}

Step 2: Adhere to the contract

Once I assign the type User to a variable, I am safe. The build will fail if data is missing or incorrect.

app.component.ts
// ✅ Valid object
const admin: User = {
  id: 1,
  username: 'Aden',
  email: 'aden@library.com',
  address: { city: 'Berlin', zip: 10115 },
  role: 'admin' // IntelliSense suggests values here!
};

// ❌ Error: Missing 'email' & Wrong Role
const guest: User = {
  id: 2,
  username: 'Guest',
  address: { city: 'Munich', zip: 80331 },

  // Error: Type '"superuser"' is not assignable to type...
  role: 'superuser'
};
💡

Interface vs. Class: A classic interview question.
Use Interfaces for pure data definitions (APIs, Props) as they generate no code.
Use Classes only when you need runtime logic (methods, new User(), instanceof checks).