Today I Learned

hashrocket A Hashrocket project

Only Pick certain properties in Typescript

In TypeScript, the Pick utility type provides a flexible way to construct new types by selecting subsets of properties from existing ones. For example, consider an interface User:

interface User {
  id: number;
  name: string;
  email: string;
  age: number;
}

// Using Pick to create a new type type
UserContactDetails = Pick<User, 'email' | 'name'>;

In this example, UserContactDetails is a new type with only the email and name properties from the User interface.

This is particularly beneficial when you must pass or manipulate only specific aspects of a complex type, ensuring type safety and reducing the risk of handling unnecessary or sensitive data. By tailoring types to particular use cases, Pick enhances code maintainability and readability, streamlining development processes in TypeScript applications.

See More #javascript TILs
Looking for help? At Hashrocket, our JavaScript experts launch scalable, performant apps on the Web, Android and iOS. Contact us and find out how we can help you.