Branded Types 7 exercises
Problem

Using Index Signatures with Branded Types

In this exercise, we're going to look at a really interesting property of branded types when they're used with index signatures.

Here we have our User and Post interfaces, along with PostId and UserId branded types:


type PostId = Brand<string, "PostId">;
type UserId = Brand<s

Loading exercise

Transcript

0:00 In this exercise, we're going to look at a really interesting property of branded types when they're used with index signatures. We have our user and we have our post here, PostID and UserID. What we're doing here is we have a database here where we have user or post.

0:14 We are creating a bunch of entries in our database based on DB PostID and DB UserID. Post and user are basically supposed to be, you're supposed to be able to get post when you access it via a PostID, and you're supposed to get user when you access it via a UserID.

0:32 They're actually returning a union of both of them. This is because this type signature is like a little interesting here. We've got a record string, and we've got a user or post being returned from that.

0:45 This means that whatever we access from this database, DB for instance 123, then the result of this is going to be post or user. Doesn't matter if we mark this as UserID or mark it as PostID. This is the idea of this exercise.

1:01 You have to come up with a type definition for this line, that means that when we access it with a UserID, then we're going to get back a user. When we access it via PostID, we're going to get back a post. That's the goal. Good luck.