...

/

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 you limit a variable that is a string or a number to a set of specific literal values. This literal type is not quite a pure enumeration type, but literal types are pretty similar to enumerations.

Why would we want to limit the values of a variable? In many cases, we actually 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 enum, but we don’t have anything like that on the client side.

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

Press + to interact
export enum TicketStatus {
Unsold,
Held,
Purchased,
Refunded,
Invalid,
}
export interface TicketData {
id: number
row: number
number: 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 string with TicketStatus, starting right away with the TicketData interface.

Making this change causes one ...