Index Signatures for Objects
Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 72 of 73.
Sometimes you need to work with objects where you know what type of values they'll contain, but you don't know the specific property names in advance. This is common when working with dictionaries, maps, or configuration objects where the keys are dynamic.
Index signatures allow you to define the type structure for such objects. The syntax uses square brackets to specify the key type and the value type:
interface StringDictionary {
[key: string]: number;
}This interface says "any string key will have a number value." You can then create objects that match this pattern:
let scores: StringDictionary = {
"alice": 95,
"bob": 87,
"charlie": 92
};Index signatures are particularly useful for scenarios like storing user preferences, caching data with dynamic keys, or working with API responses where the property names aren't known at compile time. The key type is typically string or number, while the value type can be any valid TypeScript type.
Challenge
EasyCreate an interface for a product catalog system where product categories and their stock quantities are stored dynamically.
Create an interface named ProductCatalog that uses an index signature to map string keys (product names) to number values (stock quantities).
Create a function named getStockLevel that:
- Takes two parameters:
catalogof typeProductCatalogandproductNameof typestring - Returns the stock quantity for the given product name
- Returns
0if the product doesn't exist in the catalog - Has an explicit return type of
number
Create a function named updateStock that:
- Takes three parameters:
catalogof typeProductCatalog,productNameof typestring, andnewQuantityof typenumber - Updates the stock quantity for the given product
- Returns
void
Create a function named getTotalStock that:
- Takes a parameter
catalogof typeProductCatalog - Returns the sum of all stock quantities in the catalog
- Has an explicit return type of
number
Create test data:
- Create
inventoryof typeProductCatalogwith the following products:"laptop":15"mouse":50"keyboard":25"monitor":8
Test your functions and print the following outputs:
- Call
getStockLevelwithinventoryand"laptop" - Call
getStockLevelwithinventoryand"tablet" - Call
getTotalStockwithinventory - Call
updateStockwithinventory,"mouse", and75 - Call
updateStockwithinventory,"webcam", and12 - Call
getStockLevelwithinventoryand"mouse" - Call
getStockLevelwithinventoryand"webcam" - Call
getTotalStockwithinventory
Try it yourself
// TODO: Write your code here
// Create the ProductCatalog interface
// Create the getStockLevel function
// Create the updateStock function
// Create the getTotalStock function
// Create test data - inventory object
// Test the functions and print results
console.log(getStockLevel(inventory, "laptop"));
console.log(getStockLevel(inventory, "tablet"));
console.log(getTotalStock(inventory));
updateStock(inventory, "mouse", 75);
updateStock(inventory, "webcam", 12);
console.log(getStockLevel(inventory, "mouse"));
console.log(getStockLevel(inventory, "webcam"));
console.log(getTotalStock(inventory));This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Introduction To TypeScript
1Getting Started with TS
What is TypeScript?Why Use TypeScript?Your First TypeScript CodeCompilation Process & ErrorsRecap: Introduction to TS4Working with Functions
Typing Params & Return ValuesTyping Arrow FunctionsThe 'void' Return TypeOptional Parameters with '?'Default Parameter ValuesTyping Rest ParametersDefining Function TypesRecap: Building Typed Funcs2Core Types
Basic Types: str, num, booleanThe 'any' Type: Escape HatchThe 'unknown' TypeWorking with 'null' & 'undef'Type Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Types: Aliases, Unions & Inter
Type Aliases for PrimitivesUnion Types ('|')Working with Union TypesLiteral TypesIntersection Types ('&')Combining Type AliasesRecap: Advanced Type Combos8Enums
What is a Numeric Enum?Using Numeric EnumsWhat is a String Enum?Using String EnumsHeterogeneous EnumsRecap: Using Enums11Advanced Topics
Type Assertions Type Guards: in & instanceofThe 'never' TypeNullable Types ('strictNull')Index Signatures for ObjectsRecap: Fine-Tuning Types3Data Structure: Arrays & Tuple
Typed Arrays'readonly' Modifier for ArraysWhat is a Tuple?Declaring and Accessing TuplesDestructuring TuplesReadonly TuplesMulti-dimensional Typed Arrays Spread Operator with ArraysRecap: Arrays and Tuples