typeof and keyof Type Operators

1. Welcome and Icebreaker:

  • If you could instantly know the type or keys of any object in real life, what would you inspect?

2. Outline the Session:

  • We’ll learn about the typeof and keyof type operators in TypeScript.
  • Learning Outcomes: Understand how to use these operators to get types and keys for advanced type manipulation.
  • Let’s inspect some types!

3. Concept Explanation:

  • typeof Type Operator: Gets the type of a variable or property. Useful for reusing types.
    const person = { name: "Alice", age: 30 };
    type Person = typeof person; // { name: string; age: number }
    
  • keyof Type Operator: Gets a union of all property names (keys) of a type.
    type PersonKeys = keyof Person; // "name" | "age"
    
  • These operators are powerful for creating flexible and reusable types.

4. Live Coding Demonstration:

const car = { make: "Toyota", model: "Corolla", year: 2020 };
type Car = typeof car;
type CarKeys = keyof Car;

function printKey(obj: Car, key: CarKeys) {
  console.log(`${key}: ${obj[key]}`);
}
printKey(car, "make");
printKey(car, "year");

// typeof with functions
function add(a: number, b: number): number {
  return a + b;
}
type AddType = typeof add; // (a: number, b: number) => number

5. Tasks:

  • Short Exercise:
    1. Create an object and use typeof to define its type.
    2. Use keyof to get the keys of your object type.
    3. Write a function that takes an object and a key (using keyof) and prints the value.