Generic Interfaces

1. Welcome and Icebreaker:

  • If you could define a rule that works for any type of object, what would it be?

2. Outline the Session:

  • We’ll learn how to create generic interfaces in TypeScript.
  • Learning Outcomes: Understand how to use generics with interfaces for flexible contracts.
  • Let’s make our interfaces more powerful!

3. Concept Explanation:

  • Generic Interfaces allow you to define contracts that work with any type.
  • Use <T> after the interface name to define a generic interface.
  • Useful for reusable APIs, data structures, and libraries.
  • Syntax:
    interface Container<T> {
      value: T;
    }
    

4. Live Coding Demonstration:

interface Container<T> {
  value: T;
}

const numberContainer: Container<number> = { value: 42 };
const stringContainer: Container<string> = { value: "hello" };
console.log(numberContainer, stringContainer);

// Generic interface for functions
interface Transformer<T, U> {
  (input: T): U;
}

const toLength: Transformer<string, number> = (input) => input.length;
console.log(toLength("TypeScript")); // 10

// Generic interface for a dictionary
interface Dictionary<T> {
  [key: string]: T;
}
const phoneBook: Dictionary<number> = {
  Alice: 123456,
  Bob: 654321
};
console.log(phoneBook);

5. Tasks:

  • Short Exercise:
    1. Create a generic interface Result<T> with properties: success (boolean) and data (T).
    2. Create a variable of type Result<string> and assign it a value.
    3. Create a generic interface ApiResponse<T> with properties: status (number) and body (T).
    4. Create a variable of type ApiResponse<{ id: number; name: string }> and assign it a value.