Practice: Advanced Type Manipulation Utility Functions

1. Welcome and Icebreaker:

  • If you could create a utility function for any task in your life, what would it do?

2. Outline the Session:

  • We’ll practice creating utility types and functions using advanced type manipulation.
  • Learning Outcomes: Apply advanced type operators and utility types to real-world problems.
  • Let’s get practical!

3. Concept Explanation:

  • Advanced type manipulation lets you create powerful, reusable types and functions.
  • We’ll combine conditional types, mapped types, and utility types for practical use.
  • Example: Creating a function that picks only string properties from an object.

4. Live Coding Demonstration:

type OnlyStrings<T> = {
  [K in keyof T as T[K] extends string ? K : never]: T[K]
};

type User = { id: number; name: string; email: string };
type UserStrings = OnlyStrings<User>; // { name: string; email: string }

function pickStrings<T>(obj: T): OnlyStrings<T> {
  const result = {} as OnlyStrings<T>;
  for (const key in obj) {
    if (typeof obj[key] === 'string') {
      (result as any)[key] = obj[key];
    }
  }
  return result;
}

const user: User = { id: 1, name: "Alice", email: "alice@example.com" };
console.log(pickStrings(user));

5. Tasks:

  • Short Exercise:
    1. Write a utility type that picks only number properties from an object type.
    2. Write a function that uses your utility type to extract number properties from an object.
    3. Try combining multiple utility types for more complex transformations.