Keyof with Generics

1. Welcome and Icebreaker:

  • If you could pick any property from any object, what would you choose and why?

2. Outline the Session:

  • We’ll learn how to use keyof with generics in TypeScript to access object keys in a type-safe way.
  • Learning Outcomes: Understand how to use keyof to create flexible and safe APIs.
  • Let’s unlock the power of keys!

3. Concept Explanation:

  • keyof Operator returns a union of all property names (keys) of a type.
  • When used with generics, it allows you to write functions that work with any object’s keys.
  • Syntax:
    function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
      return obj[key];
    }
    
  • This ensures you can only access valid keys, preventing runtime errors.

4. Live Coding Demonstration:

function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

const person = { name: "Alice", age: 30 };
console.log(getProperty(person, "name")); // Alice
console.log(getProperty(person, "age")); // 30
// console.log(getProperty(person, "email")); // Error: Argument of type '"email"' is not assignable to parameter of type '"name" | "age"'.

// keyof with interfaces
type Car = { make: string; model: string; year: number };
type CarKeys = keyof Car; // "make" | "model" | "year"

function printKey<T>(obj: T, key: keyof T) {
  console.log(`Key: ${key}, Value: ${obj[key]}`);
}
printKey(person, "name");
printKey(person, "age");

5. Tasks:

  • Short Exercise:
    1. Write a generic function pluck<T, K extends keyof T>(obj: T, keys: K[]): T[K][] that returns an array of values for the given keys.
    2. Create an object and use pluck to get an array of selected property values.
    3. Try to use pluck with an invalid key and observe the TypeScript error.