What is a String Enum?
Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 53 of 73.
String enums are declared by explicitly initializing each member with a string value:
enum Direction {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT"
}Unlike numeric enums that auto-increment, every member in a string enum must be explicitly initialized. The benefit is immediately clear when debugging - instead of seeing mysterious numbers like 0 or 1 in your logs, you'll see descriptive values like "UP" or "DOWN".
Challenge
EasyCreate a string enum named Direction with four members:
Upinitialized to"UP"Downinitialized to"DOWN"Leftinitialized to"LEFT"Rightinitialized to"RIGHT"
Create four variables to demonstrate the enum values:
upDirectionof typeDirectionand assign itDirection.UpdownDirectionof typeDirectionand assign itDirection.DownleftDirectionof typeDirectionand assign itDirection.LeftrightDirectionof typeDirectionand assign itDirection.Right
Print the following outputs on separate lines:
- Print the value of
upDirection - Print the value of
downDirection - Print the value of
leftDirection - Print the value of
rightDirection - Print the string value of
Direction.Up - Print the string value of
Direction.Down
Try it yourself
// TODO: Write your code here
// 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 Combos8Enums
What is a Numeric Enum?Using Numeric EnumsWhat is a String Enum?Using String EnumsHeterogeneous EnumsRecap: Using Enums3Data 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