Type Transformations Workshop (6 exercises)
solution

Manipulate String Literals Using Type Helpers

The solution here should be pretty intuitive after our previous exercise.

We'll start off with the Record type, passing it Event and string. However, this time we'll also add the Uppercase type helper around Event:

The Uppercase string manipulation type is built into TypeScript, and in this case is applied to each member of the union that is being mapped over.

Make it More Readable

Our solution can be made more readable by creating an UppercaseEvent alias as a first step:

Other String Type Helpers

There are additional string type helpers that you can use to manipulate strings such as Lowercase<> and Capitalize<>, among others:

It's so cool how TypeScript just gives you these out of the box helpers that make manipulating template literals faster and easier!

Transcript

[0:00] The solution is pretty intuitive. We look at the previous solution that we had and it was a record with these TemplateLiteralKeys and turning them into strings.
[0:10] We're doing the same thing here, except we're not having to do any union stuff, except which is add an uppercase string literal type to them. This is a type helper that's intrinsic to the language and lets you turn a string into an uppercase string.

[0:26] We can say, type UppercaseEvent = Uppercase and then Event. What we end up with is it maps over each member of the union and you end up with LOG_IN, LOG_OUT, SIGN_UP.

[0:38] There are a few of these. We can have, Capitalized, which is nice. We can also have LowercaseEvent, which doesn't do anything in this case, but if we had a "LOG_OUT" inside here, then it would turn it into the lowercase version. There are a bunch of others as well.

[0:55] I wanted to give you a brief insight into these. There's plenty of documentation on them and they're all pretty simple to understand. Yeah, TypeScript gives you these out-of-the-box helpers to even do more crazy manipulation of string literals. Very cool.