Specifying Types with Literal Types

Learn to specify types with literal types in TypeScript in this lesson.

Literal types

TypeScript lets us limit a variable that is a string or a number to a set of specific literal values. This literal type is not a pure enumeration type, but they are similar.

Why would we want to limit the values of a variable? In many cases, we have a specific, defined list of values that can be sent to a variable, and we’d like to have TypeScript insist on it. For example, in our concert app, tickets have one of five specific states: unsold, held, purchased, refunded, or invalid. On the Rails side, those values are protected with an ActiveRecord and Postgres enum, but we don’t have anything similar on the client-side.

Let’s declare a literal type based on those values. We’ll put it in our venue_reducer file:

Get hands-on with 1200+ tech skills courses.