Branded Types 7 exercises
solution

Indexing an Object with Branded Types

The solution here is pretty weird and teaches you something about the way that TypeScript understands index signatures.

The first thing I'll do is mark db as unknown because that's the type we want to change:


const db: unknown = {};

Usually if we would index into an object

Loading solution

Transcript

0:00 The solution here is pretty weird, and teaches you something about the way that TypeScript understands index signatures. The way to do this is we are going to...I marked this as unknown, because this is the type that we want to change. We want make it so, when you access via a post ID, you get a post. Now, the way that we would do that, usually, is we would say index, string, for instance, returns a post.

0:23 Now, whenever you access it via anything, you're going to get back a post. The thing that we had before was basically post or user, like this. This is essentially like a way of expressing record string post user. Let's just do that. Record string, post or user, is exactly the same syntactically as the other one. This is just a little bit of sugar syntax over the top, or a type helper over the top.

0:50 What we actually want is we want to use post ID in this slot. You can do that. Now, when you have an index post ID, you get back a post. Now, DB post ID is this, and post is actually going to be typed as post here. We want to do the same with user. It turns out, we can actually add. If I change this to post ID, I'll change this to user ID. User ID, we can actually stick that in there.

1:18 How cool is that? Two index signatures with two different brands, returning two different things. Now, user is accessed via a user ID. Super cool. I'm pretty sure we could do this with this method as well, if we fancied it. I think we could do two records here, so record, user ID, user. I've not actually checked this, just going off the cuff here.

1:44 We could use an intersection here, so if you found this solution, then this, I think, works really nicely as well. This would be a post. Yeah, this works, too. Yeah, it's really cool that you can build in this little bit of logic into your index signatures and into your databases here, because it removes a little bit of checking, basically, when you need to manually check which one is a user or which one is a post.

2:09 Very, very cool. Again, I've used this in production before. It means that, if you stick something in here and add things to this database, you can be sure what you're getting out, based on what you pass in.