Object Types and Interfaces

1. Welcome and Icebreaker:

  • If you could define an interface for your ideal app, what properties and methods would it have?

2. Outline the Session:

  • We’ll learn how to define the shape of objects using interfaces in TypeScript.
  • Learning Outcomes: Understand how to use interfaces to type objects and why they’re useful.
  • Ask questions as we go!

3. Concept Explanation:

  • Object Types describe the structure of an object (its properties and their types).
  • Interfaces are a way to name and reuse object types. They can describe properties, methods, and index signatures.
  • Syntax:
    interface User {
      id: number;
      name: string;
      isActive: boolean;
      greet(): void;
    }
    
  • Interfaces can be extended and implemented by classes.
  • Use interfaces for objects that will be used in multiple places or need to be extended.

4. Live Coding Demonstration:

// Defining an interface
interface Product {
  id: number;
  name: string;
  price: number;
  describe(): void;
}

// Using the interface
const item: Product = {
  id: 101,
  name: "Laptop",
  price: 1200,
  describe() {
    console.log(`${this.name} costs $${this.price}`);
  }
};
item.describe();

// Interface for function types
interface StringFormatter {
  (input: string): string;
}
const toUpper: StringFormatter = (input) => input.toUpperCase();
console.log(toUpper("hello"));

// Interface for index signatures
interface Dictionary {
  [key: string]: string;
}
const colors: Dictionary = {
  red: "#FF0000",
  green: "#00FF00"
};
console.log(colors["red"]);

5. Tasks:

  • Short Exercise:
    1. Define an interface Movie with properties: title (string), director (string), year (number), and a method getSummary that returns a string.
    2. Create a variable of type Movie and implement the getSummary method.
    3. Define an interface KeyValueStore for an object with string keys and number values.
    4. Create a KeyValueStore object and add some key-value pairs.