DEV Community

Nguyen Dinh Khai
Nguyen Dinh Khai

Posted on • Updated 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

Top comments (0)