Menu
Coddy logo textTech

Function: Add Items to Inv

Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 64 of 73.

challenge icon

Challenge

Easy

You are provided with the following from the previous challenge:

  • The generic interface InventoryItem<T> with properties id, quantity, and details
  • Three inventory items: bookItem, electronicItem, and clothingItem

Create a generic function named addItem that adds a new item to an existing inventory array.

The function should:

  • Use a generic type parameter T
  • Accept a parameter inventory of type InventoryItem<T>[]
  • Accept a parameter newItem of type InventoryItem<T>
  • Return a new array of type InventoryItem<T>[] containing all existing items plus the new item
  • Have an explicit return type annotation

Create the following arrays and test your function:

  • Create bookInventory as an array containing only bookItem
  • Create newBook of type InventoryItem<{ title: string; author: string }> with:
    • id: 4
    • quantity: 2
    • details: { title: "Advanced TypeScript", author: "Jane Smith" }
  • Use addItem to add newBook to bookInventory and store the result in updatedBookInventory
  • Create electronicInventory as an array containing only electronicItem
  • Create newElectronic of type InventoryItem<{ brand: string; model: string }> with:
    • id: 5
    • quantity: 1
    • details: { brand: "GadgetCorp", model: "Z500" }
  • Use addItem to add newElectronic to electronicInventory and store the result in updatedElectronicInventory

Print the following outputs:

  • Print the length of updatedBookInventory
  • Print updatedBookInventory[1].details.title
  • Print updatedBookInventory[1].details.author
  • Print the length of updatedElectronicInventory
  • Print updatedElectronicInventory[1].details.brand
  • Print updatedElectronicInventory[1].details.model
  • Print updatedElectronicInventory[0].id
  • Print updatedElectronicInventory[1].quantity

Try it yourself

// Create the generic InventoryItem interface
interface InventoryItem<T> {
  id: number;
  quantity: number;
  details: T;
}

// Create the required objects
const bookItem: InventoryItem<{ title: string; author: string }> = {
  id: 1,
  quantity: 5,
  details: { title: "TypeScript Guide", author: "John Doe" }
};

const electronicItem: InventoryItem<{ brand: string; model: string }> = {
  id: 2,
  quantity: 3,
  details: { brand: "TechCorp", model: "X200" }
};

const clothingItem: InventoryItem<{ size: string; color: string }> = {
  id: 3,
  quantity: 10,
  details: { size: "M", color: "Blue" }
};

// Print the required outputs
console.log(bookItem.id);
console.log(bookItem.quantity);
console.log(bookItem.details.title);
console.log(bookItem.details.author);
console.log(electronicItem.details.brand);
console.log(electronicItem.details.model);
console.log(clothingItem.details.size);
console.log(clothingItem.details.color);

All lessons in Introduction To TypeScript