Generic Constraints

1. Welcome and Icebreaker:

  • If you could set a rule that only certain types are allowed in your club, what would the rule be?

2. Outline the Session:

  • We’ll learn how to use generic constraints in TypeScript to limit the types that can be used with generics.
  • Learning Outcomes: Understand how to use extends to constrain generic types.
  • Let’s set some boundaries!

3. Concept Explanation:

  • Generic Constraints use the extends keyword to restrict the types that can be used as generic parameters.
  • This ensures that the generic type has certain properties or methods.
  • Syntax:
    function getLength<T extends { length: number }>(item: T): number {
      return item.length;
    }
    
  • Useful for writing functions that only work with types that have specific properties.

4. Live Coding Demonstration:

function getLength<T extends { length: number }>(item: T): number {
  return item.length;
}
console.log(getLength("hello")); // 5
console.log(getLength([1, 2, 3])); // 3
// console.log(getLength(42)); // Error: number doesn't have length

// Constraint with interface
interface Named {
  name: string;
}
function greet<T extends Named>(obj: T): string {
  return `Hello, ${obj.name}!`;
}
console.log(greet({ name: "Alice" }));
console.log(greet({ name: "Bob", age: 30 }));

5. Tasks:

  • Short Exercise:
    1. Write a generic function getFirstChar<T extends string | any[]>(item: T): string that returns the first character (for strings) or first element (for arrays as string).
    2. Write a function printName<T extends { name: string }>(obj: T) that prints the name property.
    3. Try calling these functions with valid and invalid arguments to see the type checking in action.