DEV Community

HidetoshiYanagisawa
HidetoshiYanagisawa

Posted on

Mastering TypeScript: Using the Pick Utility Type

Table of Contents

  1. Introduction
  2. Understanding the Problem
  3. Solution: The Pick Utility
  4. How to Use the Pick Utility
  5. Conclusion

Introduction

TypeScript is a superset of JavaScript, adding static typing and class-based object orientation. This enhances safety and productivity, especially for large-scale development projects. In this article, we will be exploring the Pick utility type, a powerful part of TypeScript's robust type system.

Understanding the Problem

When working with objects in TypeScript, there might be cases where you only want to use specific properties that an object holds. For instance, consider the following type:

export type SomeType = {
    propA: string;
    propB: number;
    propC: () => void;
};
Enter fullscreen mode Exit fullscreen mode

If we want to use just the propC property in a function, how do we go about it?

Solution: The Pick Utility

TypeScript provides a utility type known as Pick. This utility is used to extract certain properties from an existing type. Let's see how to use it.

How to Use the Pick Utility

First, we import SomeType.

import { SomeType } from "./path_to_file";
Enter fullscreen mode Exit fullscreen mode

This statement imports SomeType into our current script. Replace "./path_to_file" with the path where SomeType is defined.

Next, we use Pick to use propC as part of SomeType.

function usePropC(props: Pick<SomeType, 'propC'>) {
  // Now we can use 'propC'.
  // For instance:
  props.propC();
}
Enter fullscreen mode Exit fullscreen mode

Here, we're using the Pick utility type to selectively extract specific properties from an existing type. In this case, we're extracting the propC property from SomeType.

Conclusion

As demonstrated, the Pick utility in TypeScript is extremely useful when you need to selectively use properties from an existing type. It allows you to maintain type safety while using just the parts you need.

TypeScript, with its powerful and flexible type system, is capable of maintaining high productivity and safety even in large-scale projects. The Pick utility is just one example. Make sure to make the most out of it!

Top comments (0)