Template Literals 7 exercises

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:

type ObjectOfKeys = Record<TemplateLiteralKey, string>


Loading solution


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.