Beginner’s TypeScript #16
⭐ 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;
}
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">;
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">;
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:
- Medium: https://medium.com/@nhannguyendevjs/
- Dev: https://dev.to/nhannguyendevjs/
- Hashnode: https://nhannguyen.hashnode.dev/
- Linkedin: https://www.linkedin.com/in/nhannguyendevjs/
- X (formerly Twitter): https://twitter.com/nhannguyendevjs/