DEV Community

Nguyen Dinh Khai
Nguyen Dinh Khai

Posted on • Edited on

Pick, Omit and Partial in Typescript

A. Pick
Use pick to create a new type from a previous type with only a few necessary keys.

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

type PickUser = Omit<User, 'name'>;

// Resut
type PickUser = {
    name: string;
};
Enter fullscreen mode Exit fullscreen mode

B. Omit
While Pick is handy, there are occasions when the inverse operation is required. We may need to construct a type that includes everything except a few fields from a preceding type

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

type OmitUser = Omit<User, 'name'>;

// Resut
type OmitUser = {
    age: number;
};

Enter fullscreen mode Exit fullscreen mode

C. Partial
This utility type facilitates swift creation of a type with optional or undefined properties based on an existing type

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

type PartialUser = Partial<User>;

// Resut
type PartialUser = {
    name?: string | undefined;
    age?: number | undefined;
};
Enter fullscreen mode Exit fullscreen mode

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs