Objects 16 exercises

Specifying a Type with Shared Properties in TypeScript

In this exercise, we're working with three types: User, Organisation, and Product. Each type shares three properties: id, name, and imageId.

The User type has an additional age property, Organisation includes address, and Product has price:

type User = {
id: strin

Loading exercise


00:00 This is an interesting exercise. We have a type of user, a type of organization, and a type of products that we've seen before. They each have three properties in common, ID, name, and image ID. The ones that they don't have in common is user has age, organization has address, and product has price.

00:17 We have a function here called getAvatarImage. GetAvatarImage returns a URL, which basically directs to a CDN with the entity.image ID on it, and it returns an alt text saying entity name avatar. Now, your job is to work out the correct typing for this entity,

00:37 which is the parameter of getAvatarImage. You can see that we've got some test cases down here working nicely, and there's no errors down here. It's all working fine. But we want to basically make sure that this type is correct. Currently, we're getting errors down here saying entity is of type unknown,

00:55 so we can't access image ID on it. Your job is to work out the correct type for this entity. It could, of course, just be like an object type with entity.image ID or entity.name, but I would like you to keep them in sync with product user and organization at the top.

01:14 There's a really counterintuitive, beautiful way of doing it that only uses knowledge that you've learned before. There's nothing actually new in here. Good luck.