Let's say we want to use fetch to load some data from a remote JSON API. The first thing we want to do is specify an HTTP accept header of application JSON, the JSON media type. In this setup, I have the TypeScript compiler running in the background. If I save the file on the left, we can immediately see the output on the right.
Right now, I'm specifying this media type inline, but I'd rather collect all media types in a central location. As of TypeScript 2.4, we can create string enums or technically enums with string members.
I'll go ahead and create an enum media types. Within it, I'm going to define a member called JSON that maps to the application JSON media type. Down in our header subject, I can now reference the enum and replace the inline value. Let's now save this file and take a look at the compiled output.
The compiler has generated a mapping object called media types. Below that declaration, it has inserted a function in which it assigns all the values to the keys. For example, here we have the key JSON, and we sign the value application JSON to it. We get a mapping from key to value.
Notice that we're lacking a reverse mapping here. We're not mapping from application JSON to the key JSON. With other enum types in TypeScript that would be the case. If we had a numeric enum, for example, something like ports where we map the SSL port to 443, we can see that we get a generated output with two mappings. We're mapping from SSL to 443, and from 443, we map to SSL.
Note that the usage looks exactly like it does in TypeScript. We simply reference the media types object and then its JSON property. Just like with any other enum in TypeScript, we can make our string enum a const enum by adding the const modifier.
The compiler also leaves a little comment there and tells us which enum case we used. This is not a problem for file size because if you use the minifier later, this comment will disappear.