Type Transformations Workshop (7 exercises)
explainer

Template Literals in Mattermost

Let’s take a look at some application code for the open-source platform called Mattermost, an open source platform for collaboration in software.

We’re inside of the cloud.ts types file inside of the packages directory of the mattermost-webapp repo.

The main part we'll be focusing on is the MetadataGatherWireTransferKeys type:

Loading explainer

Transcript

[0:00] [0: 00] Let's take a look at some more application code. We have an application here called Mattermost, which is an open source platform for collaboration in software.
[0:08] [0: 10] Inside here, we have packages/types/src/cloud.ts. We have a few things that we've seen before. We've got this as const here, which is turning this into kind of like a literal object where all the literals are here and being used like an enum.

[0:25] [0: 25] The bit I want to look at though is MetadataGatherWireTransferKeys. This is a template string. What's going on here is that there's two parts to it. We have this _alt_payment_method here, which, if we just had that, then it would just be working like this.

[0:42] [0: 43] What it's doing there is it's creating a new type out of this by creating a union type by passing in a bunch of prefixes here. We have first_purchase, renewal_self, monthly_subscription, and annual_subscription.

[0:57] [0: 58] All of those are being calculated by using ValueOf, which we'll look at a little bit later. It's basically taking the values from an object. The object that it's grabbing is this typeof TypePurchases, which is another as const here.

[1:14] [1: 14] It's basically grabbing first_purchase, renewal_self, monthly_subscription, annual_subscription. Then it's taking those and injecting them into another string to create this longer set of strings. This is very similar to the techniques that we've already seen with template literals, except that it's using different constructs, putting them together.

[1:33] [1: 33] Finally, it can create another type here, which is a partial record of all of these different keys that then go into this object. Then this is used throughout the application. This is a really, really cool use case and shows how you can take all of these techniques and throw them together for the minimal amount of code and the maximum amount of inference.