Default Type Parameters in Generics

1. Welcome and Icebreaker:

  • If you could set a default for any setting in your life, what would it be?

2. Outline the Session:

  • We’ll learn how to use default type parameters in TypeScript generics.
  • Learning Outcomes: Understand how to provide default types for generic parameters.
  • Let’s set some smart defaults!

3. Concept Explanation:

  • Default Type Parameters allow you to specify a default type for a generic parameter if none is provided.
  • Use = to set the default type in the generic parameter list.
  • Syntax:
    function createArray<T = string>(length: number, value: T): T[] {
      return Array(length).fill(value);
    }
    
  • This makes your APIs easier to use and more flexible.

4. Live Coding Demonstration:

function createArray<T = number>(length: number, value: T): T[] {
  return Array(length).fill(value);
}
console.log(createArray(3, 5)); // [5, 5, 5]
console.log(createArray<string>(2, "hi")); // ["hi", "hi"]

// Default type parameter in a class
class Response<T = string> {
  data: T;
  constructor(data: T) {
    this.data = data;
  }
}
const r1 = new Response("Success");
const r2 = new Response<number>(200);
console.log(r1, r2);

5. Tasks:

  • Short Exercise:
    1. Write a generic function makePair<T = string, U = number>(first: T, second: U): [T, U] with default types.
    2. Call makePair with and without specifying type parameters.
    3. Create a generic class Box<T = boolean> and instantiate it with and without specifying the type.