In TypeScript, when you define an enum, you can assign specific values to each of its members. Enums can be either string-based or number-based, and you can initialize each member with a specific value. Here's how you can initialize an enum with specific values:
Numeric Enums
In numeric enums, you can initialize each member with a specific number value. If you don't assign a value, the enum will auto-increment from the previous value (default start is 0).
enum BlockType {
Header = 1,
Footer = 2,
Sidebar = 3,
Content = 4,
// If you want the next one to auto-increment, you can skip assigning a value.
// AnotherBlockType // will automatically be 5
}
console.log(BlockType.Header); // Output: 1
console.log(BlockType.Footer); // Output: 2
String Enums
String enums allow each member to be initialized with a string value. Unlike numeric enums, string enums require an explicit initialization for each member.
enum BlockType {
Header = "HEADER",
Footer = "FOOTER",
Sidebar = "SIDEBAR",
Content = "CONTENT"
}
console.log(BlockType.Header); // Output: "HEADER"
console.log(BlockType.Footer); // Output: "FOOTER"
Mixed Enums
TypeScript also allows you to create mixed enums, though it's less common. This means you can have both string and numeric values within the same enum.
enum BlockType {
Header = "HEADER",
Footer = 2,
Sidebar, // This will be auto-assigned to 3, following Footer's numeric value.
Content = "CONTENT"
}
console.log(BlockType.Footer); // Output: 2
console.log(BlockType.Sidebar); // Output: 3
Using Enums in a Map
Following the previous example where you use an enum as a key in a Map, you can define and use your initialized enum just the same. The values you assign to your enum members are what's used as keys for the map entries.
// Enum definition with values initialized
enum BlockType {
Header = "HEADER",
Footer = "FOOTER",
Sidebar = "SIDEBAR",
Content = "CONTENT"
}
// Custom type for values
interface BlockConfig {
width: number;
height: number;
backgroundColor: string;
isVisible: boolean;
}
// Map initialization
const blockConfigMap: Map<BlockType, BlockConfig> = new Map();
blockConfigMap.set(BlockType.Header, {
width: 100,
height: 50,
backgroundColor: "blue",
isVisible: true,
});
blockConfigMap.set(BlockType.Footer, {
width: 100,
height: 50,
backgroundColor: "gray",
isVisible: true,
});
// Accessing a value from the map
const headerConfig = blockConfigMap.get(BlockType.Header);
if (headerConfig) {
console.log(`Header config: width ${headerConfig.width}, height ${headerConfig.height}`);
}
// Output key-value pairs
for (const [key, value] of blockConfigMap.entries()) {
console.log(`BlockType: ${key}, Config:`, value);
}
By defining the enum with specific values, you gain more control and clarity over how enums are represented and used within your TypeScript code, especially when those enums serve as keys or identifiers in other structures.