DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

Beginner's TypeScript #16

Image description

Selectively Construct Types from Other Types

We have looked at inheriting and combining types.

Given this User interface, create a new object type that only includes the firstName and lastName properties:

interface User {
  id: string;
  firstName: string;
  lastName: string;
}
Enter fullscreen mode Exit fullscreen mode

There are a couple of solutions here that both make use of TypeScript's built-in helpers.

1️⃣ Use Omit

The first solution is to Omit.

According to TypeScript, this constructs a type with the properties of T except for those in type K.

Here is what the syntax looks like:

type MyType = Omit<User, "id">;
Enter fullscreen mode Exit fullscreen mode

What we are saying here is to create a type with everything that User has except for id.

2️⃣ Use Pick

The second solution is to use Pick, which is the inverse of Omit:

type MyType = Pick<User, "firstName" | "lastName">;
Enter fullscreen mode Exit fullscreen mode

Here we are taking User and picking its firstName and lastName properties.

Note that Pick provides autocompletion while Omit does not.

This is because you are able to omit keys that are not present on the original type, which means you end up with all of its properties. This is an advanced problem that we will tackle down the road

For now, just know that both Omit and Pick are globally available in TypeScript and are extremely useful tools.


I hope you found it useful. Thanks for reading. 🙏

Let's get connected! You can find me on:

Top comments (0)