Parameters, ReturnType, and InstanceType Utility Types

1. Welcome and Icebreaker:

  • If you could instantly know the parameters, return type, or instance type of any function or class, what would you choose?

2. Outline the Session:

  • We’ll learn about the built-in utility types Parameters, ReturnType, and InstanceType in TypeScript.
  • Learning Outcomes: Understand how to extract types from functions and classes.
  • Let’s extract some types!

3. Concept Explanation:

  • Parameters<T>: Gets the parameter types of a function type as a tuple.
  • ReturnType<T>: Gets the return type of a function type.
  • InstanceType<T>: Gets the instance type of a class constructor.
  • These are useful for type inference and advanced type manipulation.
  • Syntax:
    type Params = Parameters<(a: number, b: string) => void>; // [number, string]
    type Ret = ReturnType<() => number>; // number
    class MyClass { x = 0; }
    type Inst = InstanceType<typeof MyClass>; // MyClass
    

4. Live Coding Demonstration:

function greet(name: string, age: number): string {
  return `Hello, ${name}. You are ${age} years old.`;
}
type GreetParams = Parameters<typeof greet>; // [string, number]
type GreetReturn = ReturnType<typeof greet>; // string

class Person {
  constructor(public name: string) {}
}
type PersonInstance = InstanceType<typeof Person>;
const p: PersonInstance = new Person("Alice");

5. Tasks:

  • Short Exercise:
    1. Write a function and use Parameters and ReturnType to extract its types.
    2. Create a class and use InstanceType to get its instance type.
    3. Try using these utility types with different functions and classes.