Index Signatures for Dynamic Keys
📖 Scenario: You are building a simple app to store the number of items sold for different products in a store. The product names are not fixed and can change dynamically.
🎯 Goal: Create a TypeScript object that can hold product names as keys and their sold quantities as values using index signatures. Then, add some products and their quantities, and finally print the total quantity sold.
📋 What You'll Learn
Create an interface called
SalesRecord with an index signature for string keys and number values.Create a variable called
sales of type SalesRecord.Add three products with exact names and quantities:
'apple': 10, 'banana': 5, 'orange': 8.Create a variable called
totalSold to hold the sum of all quantities.Use a
for...in loop to iterate over sales and sum the quantities into totalSold.Print the total quantity sold using
console.log.💡 Why This Matters
🌍 Real World
Stores and inventory systems often need to track quantities of products where product names can change or be added dynamically.
💼 Career
Understanding index signatures helps in building flexible TypeScript applications that handle dynamic data structures, common in web development and backend services.
Progress0 / 4 steps