String literal types

A nice alternative to enums and string enums in TypeScript is string literal types. They provide a way to specify the value that a string must have and can actually provide the same kind of behavior as enums. One benefit of string literal types is that you can also combine them with type guards, type aliases, and unions.

The following is an example:

type Mood = "Great" | "Good" | "Bad" | "Awful"; 
const myCurrentMood: Mood = "Great"; // may only be assigned values that are part of the Mood union! 

With the Mood type defined, we can get auto-completion, as shown in the following screenshot:

While using this type, you are, of course, not allowed to pass a value that is not part of the type, hence the similarity with enums.

String literal types are also inlined. If you look at the generated code for the previous example, you'll also see that no specific code is generated for the type itself:

"use strict"; 
var myCurrentMood = "Great"; // may only be assigned values part of the Mood union! 

We won't be using those in this chapter, but it's good to know that they exist.