Using String Enums
Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 54 of 73.
String enums work particularly well as function parameters because they provide clear, readable values while maintaining type safety.
Here's how you can use a string enum in a function:
function move(direction: Direction): void {
console.log(`Moving ${direction.toLowerCase()}...`);
}When you call this function, TypeScript will only accept the predefined enum values. You can call it using move(Direction.Up), which will output "Moving up...". Your code editor will provide autocompletion for the available enum members, and TypeScript will catch any attempts to pass invalid direction values.
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
EasyYou are provided with the following from the previous challenge:
- The
Directionstring enum withUp,Down,Left, andRightmembers - Variables:
upDirection,downDirection,leftDirection, andrightDirection
Create a function named move that takes one parameter:
directionof typeDirection
The function should:
- Print a message in the format
"Moving [direction]..."where[direction]is the lowercase version of the enum's string value - Have a return type of
void
Create a function named getMovementDescription that takes one parameter:
directionof typeDirection
The function should:
- Return a string describing the movement based on the direction:
- For
Direction.Up: return"Going upward" - For
Direction.Down: return"Going downward" - For
Direction.Left: return"Turning left" - For
Direction.Right: return"Turning right" - Have an explicit return type of
string
Create a variable named playerDirection of type Direction and assign it Direction.Up.
Print the following outputs:
- Call
movewithDirection.Up - Call
movewithleftDirection - Call
movewithplayerDirection - Print the result of calling
getMovementDescriptionwithDirection.Down - Print the result of calling
getMovementDescriptionwithrightDirection - Call
movewithDirection.Right
Cheat sheet
String enums work well as function parameters, providing clear, readable values with type safety.
Use string enums in function parameters:
function move(direction: Direction): void {
console.log(`Moving ${direction.toLowerCase()}...`);
}TypeScript will only accept predefined enum values and provide autocompletion for available enum members.
Try it yourself
// From previous challenge - Direction enum and variables
enum Direction {
Up = "Up",
Down = "Down",
Left = "Left",
Right = "Right"
}
const upDirection = Direction.Up;
const downDirection = Direction.Down;
const leftDirection = Direction.Left;
const rightDirection = Direction.Right;
// TODO: Write your code here
// Create the move function that takes a Direction parameter and prints "Moving [direction]..."
// Create the getMovementDescription function that returns movement descriptions
// Create the playerDirection variable
// Call the functions and print the required outputsThis 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