🤏TypeScript Pick: Super Easy Example for Beginners

When using TypeScript, we have many possibilities available to define our variables. One very useful type is Pick. Pick is a utility type that allows you to create a new type by selecting a subset of properties from an existing type. Today we’ll do a quick and easy example of Pick by creating a menu for a bubble tea cafe, then output some text based on our order.

đź§‹ Example: Picking Features for Bubble Tea Order

We will create an interface called BubbleTea with the following properties: flavor, size, withMilk, and withSugar.

interface BubbleTea {
  flavor: 'milk tea' | 'lychee' | 'strawberry' | 'taro';
  size: 'small' | 'med' | 'large';
  withMilk: boolean;
  withSugar: boolean;
}

// Use Pick to create a smaller "Order" type
type Order = Pick<BubbleTea, 'flavor' | 'size'>;

// Example of an Order
const order: Order = {
  flavor: 'milk tea',
  size: 'small',
  // withMilk and withSugar aren't allowed here
};

// Let's display a message
function displayBubbleTeaOrder(order: Order) {
  console.log(
    `One delicious ${order.flavor} bubble tea in a ${order.size} size coming right up!`
  );
}

// Example usage
displayBubbleTeaOrder(order);
// Output: One delicious milk tea bubble tea in a small size coming right up!

From our BubbleTea interface, we created a new type called Order using Pick to limit our properties to flavor and size. We cannot use withMilk or withSugar in our new Order type because these properties were not included in our new definition.

Conclusion

We did a quick and easy example using the Pick type from TypeScript. Now you can create your very own types using Pick. Happy coding!

Leave a comment