0
0
Typescriptprogramming~5 mins

Pick type in Typescript

Choose your learning style9 modes available
Introduction

The Pick type helps you create a new type by choosing only some properties from an existing type. It keeps your code simple and focused.

When you want to use only a few properties from a big object type.
When you want to send part of an object to a function or API.
When you want to create a smaller version of a type for forms or UI.
When you want to avoid repeating property types manually.
When you want to make your code safer by limiting properties.
Syntax
Typescript
Pick<Type, Keys>

Type is the original object type.

Keys is a list of property names you want to keep, written as a union of string literals.

Examples
This creates a new type with only name and age from Person.
Typescript
type Person = {
  name: string;
  age: number;
  city: string;
};

type PersonNameAndAge = Pick<Person, 'name' | 'age'>;
This creates a type with only the model property from Car.
Typescript
type Car = {
  make: string;
  model: string;
  year: number;
};

type CarModelOnly = Pick<Car, 'model'>;
Sample Program

This program shows how to use Pick to create a smaller type with only id and username from User. Then it creates an object of that smaller type and prints it.

Typescript
type User = {
  id: number;
  username: string;
  email: string;
  isAdmin: boolean;
};

// We want a type with only id and username

type UserPreview = Pick<User, 'id' | 'username'>;

const user: User = {
  id: 1,
  username: 'alice',
  email: 'alice@example.com',
  isAdmin: false
};

const preview: UserPreview = {
  id: user.id,
  username: user.username
};

console.log(preview);
OutputSuccess
Important Notes

You can only pick properties that exist in the original type.

Pick helps keep your types DRY (Don't Repeat Yourself).

Summary

Pick creates a new type by selecting specific properties from another type.

It helps you work with smaller, focused types.

Use it to make your code safer and easier to maintain.