Literal Types
Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 33 of 73.
Literal types let you constrain a variable to exact, specific values rather than broad categories. Instead of accepting any string, you can limit it to only "left", "right", "up", or "down".
A literal type uses the exact value as the type itself.
You can create literal types for strings, numbers, or booleans:
let direction: "left" = "left"; // Only "left" is allowed
let count: 42 = 42; // Only the number 42 is allowed
let isReady: true = true; // Only true is allowedLiteral types become powerful when combined with union types, creating a controlled set of allowed values. This is perfect for scenarios like directions, status codes, or configuration options:
type Direction = "left" | "right" | "up" | "down";
type Status = "pending" | "approved" | "rejected";
let playerMove: Direction = "up"; // Valid
let orderStatus: Status = "pending"; // Valid
// let invalid: Direction = "diagonal"; // Error!This approach gives you the flexibility of multiple options while maintaining strict type safety. TypeScript will catch typos and invalid values at compile time, making your code more reliable than using general string types.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyCreate a type alias named Direction for the literal types "left" | "right" | "up" | "down".
Create a type alias named GameState for the literal types "menu" | "playing" | "paused" | "gameover".
Create a type alias named Difficulty for the literal types "easy" | "medium" | "hard".
Now declare the following variables using your type aliases:
- Declare a variable named
playerDirectionof typeDirectionand assign it the value"up" - Declare a variable named
currentStateof typeGameStateand assign it the value"playing" - Declare a variable named
selectedDifficultyof typeDifficultyand assign it the value"medium"
Create a function named movePlayer that accepts a parameter called direction of type Direction and returns a string. The function should return a message in the format "Moving [direction]".
Create another function named updateGameState that accepts a parameter called state of type GameState and returns a string. The function should return a message in the format "Game state: [state]".
Call your functions with the variables you created and print the results:
- Call
movePlayerwithplayerDirectionand print the result - Call
updateGameStatewithcurrentStateand print the result - Print the value of
selectedDifficulty
Print each result on a separate line in the order specified above.
Cheat sheet
Literal types constrain variables to exact, specific values rather than broad categories:
let direction: "left" = "left"; // Only "left" is allowed
let count: 42 = 42; // Only the number 42 is allowed
let isReady: true = true; // Only true is allowedCombine literal types with union types to create controlled sets of allowed values:
type Direction = "left" | "right" | "up" | "down";
type Status = "pending" | "approved" | "rejected";
let playerMove: Direction = "up"; // Valid
let orderStatus: Status = "pending"; // ValidThis provides type safety by catching typos and invalid values at compile time while maintaining flexibility with multiple options.
Try it yourself
// TODO: Write your code here
// Create type aliases for Direction, GameState, and Difficulty
// Declare variables using your type aliases
// Create the movePlayer and updateGameState functions
// Call the functions and print the resultsThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Introduction To TypeScript
1Getting Started with TS
What is TypeScript?Why Use TypeScript?Your First TypeScript CodeCompilation Process & ErrorsRecap: Introduction to TS4Working with Functions
Typing Params & Return ValuesTyping Arrow FunctionsThe 'void' Return TypeOptional Parameters with '?'Default Parameter ValuesTyping Rest ParametersDefining Function TypesRecap: Building Typed Funcs2Core Types
Basic Types: str, num, booleanThe 'any' Type: Escape HatchThe 'unknown' TypeWorking with 'null' & 'undef'Type Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Types: Aliases, Unions & Inter
Type Aliases for PrimitivesUnion Types ('|')Working with Union TypesLiteral TypesIntersection Types ('&')Combining Type AliasesRecap: Advanced Type Combos3Data Structure: Arrays & Tuple
Typed Arrays'readonly' Modifier for ArraysWhat is a Tuple?Declaring and Accessing TuplesDestructuring TuplesReadonly TuplesMulti-dimensional Typed Arrays Spread Operator with ArraysRecap: Arrays and Tuples