#typescript
#types
#advanced
Day 14: Literal Types and Enums
Exact Values
Welcome to Day 14! Sometimes string or number is too broad. sometimes we want specific strings or numbers.
Literal Types
You can use a specific string or number as a type properly.
let direction: "left" | "right" | "up" | "down";
direction = "left"; // OK
// direction = "diagonal"; // Error
This is incredibly powerful when paired with Union Types.
Enums
Enums (Enumerations) allow you to define a set of named constants.
Numeric Enums
By default, they are numbers starting at 0.
enum Direction {
Up, // 0
Down, // 1
Left, // 2
Right, // 3
}
move(Direction.Up);
String Enums
You can initialize them with strings for better debugging.
enum Role {
User = "USER",
Admin = "ADMIN",
}
Literals vs Enums
- Literal Types: Lightweight, simpler, no runtime code generated. Great for simple unions.
- Enums: More rigid, generate actual JavaScript code (an object). Good if you need to iterate over the values or use them as actual values at runtime.
Modern TS Advice: Lean towards Literal Types or const objects (as const) unless you specifically need Enum features.
Challenge for Today
- Create a function
move(direction: "Up" | "Down" | "Left" | "Right"). - Try to call it with βNorthβ.
- Create an Enum
StatuswithPending,InProgress,Done. - Create a function
updateStatus(s: Status).
See you on Day 15 for the big one: Generics!