Pick, Omit, and Record Utility Types

1. Welcome and Icebreaker:

  • If you could pick, omit, or record any details about your day, what would you choose?

2. Outline the Session:

  • We’ll learn about the built-in utility types Pick, Omit, and Record in TypeScript.
  • Learning Outcomes: Understand how to use these types to create new object types from existing ones.
  • Let’s manipulate some types!

3. Concept Explanation:

  • Pick<T, K>: Creates a type by picking a set of properties K from type T.
  • Omit<T, K>: Creates a type by omitting a set of properties K from type T.
  • Record<K, T>: Creates a type with keys K and values of type T.
  • These are useful for creating new types from existing ones.
  • Syntax:
    type NameAndEmail = Pick<User, 'name' | 'email'>;
    type UserWithoutEmail = Omit<User, 'email'>;
    type UserRoles = Record<string, 'admin' | 'user'>;
    

4. Live Coding Demonstration:

type User = { id: number; name: string; email: string };
type NameAndEmail = Pick<User, 'name' | 'email'>;
type UserWithoutEmail = Omit<User, 'email'>;
type UserRoles = Record<string, 'admin' | 'user'>;

const user: NameAndEmail = { name: "Alice", email: "alice@example.com" };
const user2: UserWithoutEmail = { id: 1, name: "Bob" };
const roles: UserRoles = { alice: 'admin', bob: 'user' };

5. Tasks:

  • Short Exercise:
    1. Create a type Product and use Pick to select some properties.
    2. Use Omit to exclude a property from Product.
    3. Use Record to create a type mapping product IDs to product names.