Specifying Types with Literal Types
Explore how TypeScript's literal types let you limit variables to specific string or numeric values for stronger type safety. Learn to declare literal types for application states, implement discriminated unions for type guards in reducers, and understand challenges with exhaustiveness checking. This lesson helps you write more robust and error-resistant TypeScript code.
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:
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 ...