Use Pick and Omit to Reshape TypeScript Object Types
Reshape your object types in TypeScript using Pick and Omit. Keep your code DRY, consistent, and easier to maintain.
Duration
3 min
Access
Free
Transcript
Available
Reshape your object types in TypeScript using Pick and Omit. Keep your code DRY, consistent, and easier to maintain.
Duration
3 min
Access
Free
Transcript
Available
Video Transcript
When you're working with large object types, you often need a slightly different version of the same shape. Instead of rewriting it from scratch, you can derive it. TypeScript has built-in tools for that. Let's say you have this user type. It has an ID, name, email, and maybe it can have more properties.
And you want a type with just the ID and name. For this, you can use the Pick type utility. Let's create a type named public user and pass the base type user and then a union list of the attributes you want, in this case id and name. Pick works on object types and lets you select exactly the keys you want. Notice here that to list multiple keys, you need to use an union.
Then this will create a type that it have only the ID and the name. It's clean, don't repeat yourself, and type safe. So if for some reason you add a new attribute here the public users is still the ID and the name now let's do the opposite let's create a private user type in this case you want every property except the email so for that you use omit Let's pass the base type and the list of properties or attributes you don't want. In this case you don't want the email. Like pic, omit works on object shapes but in this time it helps you create focused versions of your data for UIs or APIs.
Private user is only ID, name or age. What happens if I add another one here? Let's add something like a password. Public user will only have id and name, and private user will have everything but email. So deriving types this way keeps your code consistent.
If users change, the rest of the types will automatically update. This prevents small bugs and reduces duplication. But don't overdo it. If the new type needs extra logic or maybe you need only to use a couple of fields, Maybe a custom type could be cleaner. For example, if the public user ID need to be different, you can do this and this, but it starts to look weird, so maybe in this case is better to just duplicate.
Use pick and omit when they make your types cleaner, not just shorter.