JS Learning

Interfaces

TypeScript Type SystemSection 4 of 4beginner

Topic Overview

Take your time to understand each concept. Practice with the examples below!

Interfaces are like blueprints for objects. They define what properties an object should have and what types those properties should be. Think of them as contracts that objects must follow!

What are Interfaces? An interface is a way to name and describe the shape of an object. It's like creating a template that says "any object of this type must have these specific properties."

Why Use Interfaces?

  • Clear contracts:Everyone knows what properties an object should have
  • Type safety:Can't forget required properties or use wrong types
  • IntelliSense:Amazing autocomplete for object properties
  • Reusability:Define once, use many times
  • Documentation:Interfaces serve as clear documentation

Interface Basics:

  • Required properties:Must be present in the object
  • Optional properties:Add ? to make them optional
  • Readonly properties:Can't be changed after creation
  • Method signatures:Define what methods an object should have

Real-World Examples:

  • User profiles:Define what user data looks like
  • API responses:Ensure you handle all response fields
  • Configuration objects:Specify all config options
  • Component props:Define what props a React component accepts

Interface vs Type:

  • Interfaces:Best for object shapes, can be extended
  • Type aliases:More flexible, can represent any type
  • Both work for objects, but interfaces are preferred
  • Interfaces can be merged, types cannot

Advanced Features:

  • Extending interfaces:Build on existing interfaces
  • Implementing interfaces:Classes can implement interfaces
  • Index signatures:Allow dynamic property names
  • Function types:Interfaces can describe functions too!

Example

// Interface definition
interface User {
id: number;
name: string;
email: string;
isActive?: boolean; // Optional property
}
// Using the interface
const user1: User = {
id: 1,
name: "Alice Johnson",
email: "alice@example.com",
isActive: true
};
const user2: User = {
id: 2,
name: "Bob Smith",
email: "bob@example.com"
// isActive is optional, so we can omit it
};
// Function using interface
function getUserInfo(user: User): string {
return `${user.name} (${user.email})`;
}
console.log(getUserInfo(user1));