Pick, Omit and Partial in Typescript
Nguyen Dinh Khai

Nguyen Dinh Khai @dinhkhai0201

About: I’m Khai. I’m a web, mobile and blockchain developer living in Da Nang, Vietnam. I am a fan of technology, programming, and writing. I’m also interested in sports and photography.

Location:
Viet Nam
Joined:
Feb 24, 2024

Pick, Omit and Partial in Typescript

Publish Date: Feb 24 '24
0 0

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

Comments 0 total

    Add comment