Finally, consider a task that involves managing a store's inventory. Here, we can use a Map where product names are keys, and quantities are values. This approach facilitates easy management of store inventories with TypeScript for added type safety.
let storeInventory: Map<string, number> = new Map();
storeInventory.set("Apples", 100);
storeInventory.set("Bananas", 80);
storeInventory.set("Oranges", 90); // Initializing an inventory
storeInventory.set("Apples", (storeInventory.get("Apples") || 0) + 20); // Updating the number of apples in inventory
let prod: string = "Apples"; // A product to be checked
console.log(`Total ${prod} in stock: ${storeInventory.get(prod)}`);
// Check if a product is in stock
prod = "Mangoes";
if (storeInventory.has(prod)) { // If mangoes exist in inventory
console.log(`${prod} are in stock.`);
} else { // If mangoes don't exist in inventory
console.log(`${prod} are out of stock.`);
}
Using TypeScript's Maps, we achieve more robust and maintainable solutions for managing inventory data.