Books/TypeScript Essentials/Interfaces and Type Aliases

    Interfaces and Type Aliases

    Interfaces and Type Aliases

    When AI generates code for your app, you'll see interface and type everywhere. They define the shape of your data — what properties an object has and what type each property is.

    Interfaces: Defining Object Shapes

    An interface is a blueprint for an object:

    interface User {
      id: number;
      name: string;
      email: string;
      isAdmin: boolean;
    }

    Now any object labeled as a User must have exactly those properties with those types:

    // ✅ Valid
    const alice: User = {
      id: 1,
      name: "Alice",
      email: "alice@example.com",
      isAdmin: false,
    };
    
    // ❌ Error — missing 'email' property
    const bob: User = {
      id: 2,
      name: "Bob",
      isAdmin: true,
    };

    What to ask your AI: "Can you create an interface for a [blog post / product / order] with all the fields I'll need?"

    Optional Properties

    Not every property is always required. Use ? to make properties optional:

    interface User {
      id: number;
      name: string;
      email: string;
      isAdmin: boolean;
      avatarUrl?: string;    // Optional — might not exist
      bio?: string;          // Optional
    }
    
    // ✅ Valid — optional fields can be left out
    const alice: User = {
      id: 1,
      name: "Alice",
      email: "alice@example.com",
      isAdmin: false,
    };

    You'll see this pattern constantly in AI-generated code. API responses often have optional fields.

    Type Aliases: Another Way to Define Types

    The type keyword creates a type alias — a name for any type:

    // Same as the interface above
    type User = {
      id: number;
      name: string;
      email: string;
      isAdmin: boolean;
    };

    For objects, interface and type work almost identically. You'll see both in AI-generated code.

    When Types Shine: Union and Literal Types

    type is especially useful for things interfaces can't do:

    // Union of literal strings
    type Status = "loading" | "success" | "error";
    
    // Union of different shapes
    type ApiResponse = SuccessResponse | ErrorResponse;
    
    // Simple alias
    type UserId = string;

    Interface vs Type — When You'll See Each

    Use CaseYou'll Typically See
    Object shapes (user, product, etc.)interface
    React component propsinterface
    Union types (this OR that)type
    Simple aliasestype
    API response shapesEither

    The practical rule: They're mostly interchangeable for objects. Don't worry about choosing — AI will pick one and be consistent.

    What to ask your AI: "In this codebase, should I use interface or type for defining data shapes? What's the existing convention?"

    Extending Interfaces

    Interfaces can build on other interfaces:

    interface User {
      id: number;
      name: string;
      email: string;
    }
    
    // AdminUser has everything User has, plus role
    interface AdminUser extends User {
      role: "admin" | "superadmin";
      permissions: string[];
    }

    This is like saying "an AdminUser is a User with extra fields." You'll see this when AI creates related data types.

    Nested Types

    Real-world data is often nested. Interfaces can reference other interfaces:

    interface Address {
      street: string;
      city: string;
      state: string;
      zip: string;
    }
    
    interface User {
      id: number;
      name: string;
      email: string;
      address: Address;           // Nested object
      orders: Order[];            // Array of another interface
    }
    
    interface Order {
      id: number;
      total: number;
      items: OrderItem[];
    }
    
    interface OrderItem {
      productId: number;
      name: string;
      quantity: number;
      price: number;
    }

    When you see this in AI-generated code, trace the relationships: A User has an Address and multiple Orders, each Order has multiple OrderItems.

    What to ask your AI: "Can you show me the data model for this app? List all the interfaces and how they relate to each other."

    Common Patterns in AI-Generated Code

    Here are real patterns you'll encounter:

    API Response Types

    interface ApiResponse<T> {
      data: T;
      success: boolean;
      message?: string;
    }
    
    // Used like:
    type UserResponse = ApiResponse<User>;
    // Equivalent to: { data: User; success: boolean; message?: string }

    The <T> is a generic — think of it as a placeholder. We'll touch on generics more in the functions tutorial.

    Form Data

    interface LoginForm {
      email: string;
      password: string;
      rememberMe?: boolean;
    }
    
    interface SignupForm {
      name: string;
      email: string;
      password: string;
      confirmPassword: string;
    }

    Database Models

    interface Product {
      id: string;
      name: string;
      description: string;
      price: number;
      category: string;
      inStock: boolean;
      createdAt: Date;
      updatedAt: Date;
    }

    Component Props (React)

    interface ButtonProps {
      label: string;
      onClick: () => void;
      variant?: "primary" | "secondary" | "danger";
      disabled?: boolean;
      size?: "sm" | "md" | "lg";
    }

    Reading Interfaces in AI Code

    When you encounter an interface you don't understand, ask yourself:

    1. What entity does it represent? (User, Product, Order, etc.)
    2. Which fields are required vs optional? (Look for ?)
    3. Are there nested types? (Fields that reference other interfaces)
    4. Are there restricted values? (Union types like "admin" | "user")

    What to ask your AI: "I see this interface in the code: [paste it]. Can you explain each field and why it's needed?"

    What's Next?

    Now that you understand how data is shaped, the next tutorial covers functions and their types — how TypeScript describes what goes in and what comes out.


    🌐 www.genai-mentor.ai