Type Transformations Workshop (6 exercises)
solution

Use a Utility Type to Create An Object From A Union

The solution is to use the Record type.

Passing in TemplateLiteralKey and string as the type parameters will create an object type that has all of the keys from TemplateLiteralKey and the values will be string:

Going Further

Similar to other template literal behaviors we've seen, we can add anything we want to TemplateLiteralKey and it will be reflected in ObjectOfKeys.

For example, if we add "admin" to the first template literal:

We end up with additional keys being created:

While this is a great way to convert template literals into objects, with this pattern you can't individually set the types of the properties.

We'll get to that in the key remapping section.

Transcript

[0:00] The solution here is to use a record type where what we're doing is we're basically creating any number of object keys. We want them all to be strings here. What that means is we get this really nice type here where we can just add anything we want this, for instance, admin or something.
[0:20] We've got this. Now, we end up with a bunch of more properties inside here, too. If we want to say ID name or I don't know, something, for instance, or email, let's say, then what we end up with is even more keys added to this. This is a neat way that you can start turning a template literal string into an object if you want to.

[0:42] These are all cast two strings here. In this particular pattern, we can't give each value a different one based on the shape of the key. We'll look at that when we get to key remapping in, I think, module 5 of this.