Objects 16 exercises

Common Keys of Unions of Objects in TypeScript

The simplest solution here turns out to be the correct one.

We can indeed pass in a union of User, Organisation, and Product as the entity type. This means that any of these types would be accepted:

const getAvatarImage = (entity: User | Organisation | Product) => {
// ...

Loading solution


00:00 Okay, the simplest solution here is actually the correct solution. We can simply pass in a union of user or organization or product. And when we do that, what we're saying to TypeScript is you can pass in any one of these. It doesn't matter which one. So all of these like test cases down the bottom will work.

00:20 And you notice that we still get access to the properties that they have in common. So we still get access to ID, image ID and name. We just don't get access to age, address and price. And this is really odd because you might think, Oh, what? I would love to be able to access age on it because age is available on one of the members.

00:41 It's just that it's not available on all of the members. And TypeScript will yell at you if you don't get that right. So this means then this is kind of like a narrowing thing, really. We would have to say now if age in entity, then we would know that it's an entity.age. So we'd know that this is a user, for instance.

01:01 So this is actually a really nice way that you can just very quickly get all of the properties in common of a bunch of different types without needing to define a separate type. You just say, OK, define these as a union of user organization and product.

01:18 And then I know that inside my function, I'm going to be able to access the properties in common on those. And if I need to, I can narrow down further later on. Really nice little trick.