We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Literal Types

Many other statically typed languages (including Go) don't have nearly as extensive and powerful type systems as TypeScript. It should be obvious because it's in the name, but TypeScript truly has a massive type system.

Literal types are incredibly powerful for narrowing the possible values of a variable.

  • A string can have an infinite number of values.
  • A number can have an infinite number of values.

So what if we want to declare a "direction" variable?

function move(direction: string) {
  // Implementation...
}

This kinda sucks... direction can be any string! To be fair, in many languages enums are used to solve this problem. And while TypeScript does have enums, which we'll cover later, literal types are a more lightweight solution. A literal value can be used as a type:

function move(direction: "north") {
  // Implementation...
}

Now direction can only be "north"!