Use 'in' operator to transform a union to another union

Transform a union to another union, using the 'in' operator as a kind of for-loop.

This pattern can be used for almost any kind of transformation - here, I add a dynamic key.

Discuss on Twitter

Transcript

Folks, the challenge for today is to take this union type here, type user, type post, type comment, and dynamically add the ID type, which is going to be userID, postID, and commentID. As you can see, the EntityWithID is currently not really...we could be auto generating this and we're not. Let's try and improve on this.

We're going to say type EntityWithID = -- we're going to use the sort of same trick as we did last time -- which it's going to be [EntityType in Entity ["type"] ]. This is going to be an object where the type is the EntityType. Now, so far, what this will do is we'll get to this point where we have comments where the type is 'comment'.

We're doing pretty well there, but really what we needed to turn this into a union. To turn into a union, we basically go EntityType here. This means now that we now have our type: 'Comment' or type: 'User', but we haven't really added anything here. We just created the same type again. We haven't added the IDs.

The way that we do this is we say, "OK, we've got this object here, which is representing this." We say and we're going to make a record where it's going to be entity type. In fact, we're going to use a new string literal type where it's going to be entity type and then ID. That's going to be a string.

now commentID is going to appear 1, 2, 3. This little thing here, we're basically saying we have the type entity type and the record, which is another way of saying a string or rather an object with this is the key, with this as the value of that key.

If we remove this little end, then commentID no longer exists. If we remove this bit here, then we don't need to pass the type anymore. We just pass the commentID. There we go. That's how we handle it. We've used a little bit of a quite modern TypeScript here to handle this, but it's perfectly possible to do this, of course, if we didn't then go post, then we need to pass in a post ID.

Thanks so much for your time.

More Tips