Skip to main content

What is an Interface?

An interface is like a “contract” or “blueprint” that defines what properties an object must have and their types. Think of it like an architectural plan: it defines the structure before you build.

Basic Syntax

interface InterfaceName {
  property1: type;
  property2: type;
  optionalProperty?: type;  // The ? indicates it's optional
}

Simple Example

interface Person {
  name: string;
  age: number;
  email?: string;  // Optional
}

const juan: Person = { name: "Juan", age: 25 }; // ✅ Valid
const pedro: Person = { name: "Pedro" };         // ❌ Missing 'age'
const ana: Person = { 
  name: "Ana", 
  age: 30, 
  email: "[email protected]"  // ✅ Optional properties can be included
};

Real-World Example: Category Interface

From our project, this interface describes the data structure the API sends for each category:
main.ts
interface Category {
  id: number;       // Unique identifier (e.g., 1, 2, 3)
  name: string;     // Category name (e.g., "Electronics", "Clothes")
  image: string;    // URL of the category image
  slug: string;     // URL-friendly version of name (e.g., "electronics")
}

Nested Interfaces: Product

Notice how the category property uses the Category interface we just defined:
main.ts
interface Product {
  id: number;           // Unique product identifier
  title: string;        // Product name/title
  slug: string;         // URL-friendly title
  price: number;        // Product price (number, not string!)
  description: string;  // Detailed description
  category: Category;   // Complete Category object (nested interface)
  images: string[];     // Array of image URLs (can have multiple)
}

Using the Product Interface

const laptop: Product = {
  id: 1,
  title: "Gaming Laptop",
  slug: "gaming-laptop",
  price: 1299.99,
  description: "High-performance laptop for gaming",
  category: {
    id: 2,
    name: "Electronics",
    image: "https://example.com/electronics.jpg",
    slug: "electronics"
  },
  images: [
    "https://example.com/laptop-1.jpg",
    "https://example.com/laptop-2.jpg"
  ]
};

Application State Interface

Interfaces are perfect for defining your app’s state structure:
main.ts
interface AppState {
  status: LoadingState;     // Current loading state (uses the enum)
  products: Product[];      // Array of products (uses Product interface)
  error: string | null;     // Error message OR null if no error
}
Then use it to create your state object:
main.ts
let appState: AppState = {
  status: LoadingState.Idle,  // Start in "idle" state
  products: [],               // No products at start (empty array)
  error: null                 // No errors at start
};

Why Use Interfaces?

1. The Editor Warns You About Missing Properties

const broken: Product = {
  id: 1,
  title: "Test"
  // ❌ Error: Missing required properties: slug, price, description, category, images
};

2. Autocompletion While Coding

function showProduct(product: Product) {
  console.log(product.); // Editor suggests: id, title, price, etc.
}

3. Catch Typos Before Running

const product: Product = { /* ... */ };
console.log(product.titel); // ❌ Error: Did you mean 'title'?

4. Self-Documenting Code

Anyone reading your code knows exactly what data structure to expect:
function createProductCard(product: Product): string {
  // I know product has: id, title, price, description, category, images
}

Optional Properties

Use ? to mark properties that might not always exist:
interface User {
  id: number;
  name: string;
  email?: string;      // Might not have email
  phone?: string;      // Might not have phone
}

const user1: User = { id: 1, name: "John" }; // ✅ Valid
const user2: User = { id: 2, name: "Jane", email: "[email protected]" }; // ✅ Also valid

Arrays in Interfaces

interface Product {
  images: string[];  // Array of strings
}

const product: Product = {
  images: [
    "image1.jpg",
    "image2.jpg",
    "image3.jpg"
  ]
};

Interfaces vs Types

You might also see type used similarly:
// Interface
interface Product {
  id: number;
  title: string;
}

// Type (does the same thing here)
type Product = {
  id: number;
  title: string;
};
For object shapes, interface is preferred. Use type for unions, primitives, and complex types.

Next Steps

Build docs developers (and LLMs) love