Generics: Introduction and Functions

1. Welcome and Icebreaker:

  • If you could make any tool or function work with anything, what would it be?

2. Outline the Session:

  • We’ll learn about generics in TypeScript: what they are, why they’re useful, and how to write generic functions.
  • Learning Outcomes: Understand the basics of generics and how to create reusable, type-safe code.
  • Let’s get generic!

3. Concept Explanation:

  • Generics allow you to write code that works with any type, while still maintaining type safety.
  • Use angle brackets <T> to define a generic type parameter.
  • Generics are especially useful for functions and data structures that should work with multiple types.
  • Syntax:
    function identity<T>(arg: T): T {
      return arg;
    }
    
  • You can specify the type when calling the function, or let TypeScript infer it.

4. Live Coding Demonstration:

function identity<T>(value: T): T {
  return value;
}
console.log(identity<string>("hello")); // "hello"
console.log(identity<number>(42)); // 42

// Generic function for arrays
function firstElement<T>(arr: T[]): T | undefined {
  return arr[0];
}
console.log(firstElement([1, 2, 3])); // 1
console.log(firstElement(["a", "b", "c"])); // "a"

// Generic function with multiple types
function merge<T, U>(a: T, b: U): [T, U] {
  return [a, b];
}
console.log(merge(1, "one")); // [1, "one"]

5. Tasks:

  • Short Exercise:
    1. Write a generic function wrapInArray that takes a value of any type and returns it in a single-element array.
    2. Write a generic function getLastElement that returns the last element of an array of any type.
    3. Write a generic function swap that takes a tuple of two elements and returns a new tuple with the elements swapped.