...

/

Specifying Types with Literal Types

Specifying Types with Literal Types

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

We'll cover the following...

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:

export type TicketStatus =
| "unsold"
| "held"
| "purchased"
| "refunded"
| "invalid"
export interface TicketData {
id: number
number: number
row: number
status: TicketStatus
}

This declares a new type, TicketStatus, that can only have the five-string values listed. Now, in places that use that value, we replace the declaration of a string with TicketStatus, starting immediately with the TicketData interface. ...