Objects 16 exercises
explainer

A Quirk of Omit in TypeScript

Here's an interesting quirk with the Omit utility type in TypeScript: it allows you to exclude properties that don't exist on an object.

For example, consider this User type, which contains properties id, name, and email:


type User = {
id: number;
name: string;
email: s

Loading explainer

Transcript

00:00 I wanted to show you an interesting little thing with omit, which is it's possible to use omit to omit properties which don't exist on the object. With pick we saw that, okay, we've got a user type at the top. We've got ID, name and email.

00:14 And what you can do is with pick, you can't pass in stuff that doesn't exist. So we can pass in email, we can pass in name, but we can't pass in things like phone number like this. This will error and say phone number does not satisfy the constraint key of user.

00:31 And key of user means the keys of user, ID, name and email. But if we do exactly the same with omit, you notice it just, like, it's fine. It's happy. And it returns the same type as it got in. So why does it let you do this? Well, when TypeScript kind of implemented this stuff, it had a choice.

00:49 It could either do a kind of strict version of omit where it only allowed the certain keys, ID, name and email. Or it could do a loose version of omit. And it turned out that the more popular version at that time was the loose version of omit.

01:03 And when TypeScript adds global types into the whole, you know, global scope, because these are available globally, don't need to import these from anywhere. What it's saying is, okay, we probably need to choose the looser option because that's going to be more compatible and error less. So you can create your own version of strict omit.

01:21 And I'm going to show you how to do that in, I think, another exercise. But I think the loose version of omit is basically fine for most cases. You just need to be a little bit wary because sometimes it won't error at you in the way that you expect it to. So there you go. There's no autocomplete on omit.

01:38 And you can pass in various things which will break a little bit. And I've added some links just down here to show all of the decisions that led into that within TypeScript's team.