The Omit Utility Type in TypeScript
The Omit
utility type is the most efficient way to exclude particular properties from a type in TypeScript.
In this case, we'll create a new ProductWithoutId
type and use Omit
to give us everything from Product
except for the id
:
type ProductWithoutId = Omit<Product, "id">;
Transcript
00:00 Okay, the correct way to do this is to use omit. And omit, just like pick, operates on objects, and so we can omit product ID. Wow, okay, if we grab that out into its own type, let's say type product without ID equals this,
00:19 then we can just pull this into the parameter type here, so product without ID. We hover over that, boom, we've got name, price, description, string. So nice that it just shows you the actual type readout here. Super cool, and now our types are working. And if we try to pass ID into here, then we're going to get an error.
00:38 Object literal may only specify known properties, and ID does not exist in type product without ID. Very, very cool. The result, of course, the other solution, which is basically extracting out the product info, and then the with ID, and then creating an interface which extends both of them. But this is a lot more lines of code,
00:56 and again, we're obscuring what our actual product is and what attributes it actually has. So of course, this is perfectly fine, but I think I just prefer this solution, because again, product stays as the source of truth, and it just works. And of course, you can pass in multiple of these if you want to.
01:16 So you can have ID or name into here to omit multiple properties, just with the same as PIC. And this is like the reverse of PIC. Super duper cool and very widely useful.