0
0
Typescriptprogramming~15 mins

Index signatures for dynamic keys in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
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
1
Create the SalesRecord interface
Create an interface called SalesRecord with an index signature that allows string keys and number values.
Typescript
Need a hint?

Use [key: string]: number; inside the interface to allow dynamic keys.

2
Create the sales object with products
Create a variable called sales of type SalesRecord and assign it an object with these exact entries: 'apple': 10, 'banana': 5, 'orange': 8.
Typescript
Need a hint?

Use const sales: SalesRecord = { ... } to create the object with the exact keys and values.

3
Calculate total quantity sold
Create a variable called totalSold and set it to 0. Then use a for...in loop with variable product to iterate over sales and add each quantity to totalSold.
Typescript
Need a hint?

Initialize totalSold to 0. Use for (const product in sales) to loop through keys and add sales[product] to totalSold.

4
Print the total quantity sold
Use console.log to print the value of totalSold.
Typescript
Need a hint?

Use console.log(totalSold); to display the total quantity sold.