Menu
Coddy logo textTech

関数:在庫にアイテムを追加する

CoddyのJavaScriptジャーニー「Introduction To TypeScript」セクションの一部。レッスン 64/73。

challenge icon

チャレンジ

簡単

前回のチャレンジから、以下の内容が提供されています:

  • プロパティ idquantitydetails を持つジェネリックインターフェース InventoryItem<T>
  • 3つの在庫アイテム:bookItemelectronicItemclothingItem

既存の在庫配列に新しいアイテムを追加する、addItem という名前のジェネリック関数を作成してください。

この関数は以下の要件を満たす必要があります:

  • ジェネリック型パラメータ T を使用すること
  • InventoryItem<T>[] 型のパラメータ inventory を受け取ること
  • InventoryItem<T> 型のパラメータ newItem を受け取ること
  • 既存のすべてのアイテムに新しいアイテムを加えた、InventoryItem<T>[] 型の新しい配列を返すこと
  • 明示的な戻り値の型注釈を持つこと

以下の配列を作成し、関数をテストしてください:

  • bookItem のみを含む配列として bookInventory を作成します
  • 以下の内容を持つ InventoryItem<{ title: string; author: string }> 型の newBook を作成します:
    • id: 4
    • quantity: 2
    • details: { title: "Advanced TypeScript", author: "Jane Smith" }
  • addItem を使用して newBookbookInventory に追加し、その結果を updatedBookInventory に保存します
  • electronicItem のみを含む配列として electronicInventory を作成します
  • 以下の内容を持つ InventoryItem<{ brand: string; model: string }> 型の newElectronic を作成します:
    • id: 5
    • quantity: 1
    • details: { brand: "GadgetCorp", model: "Z500" }
  • addItem を使用して newElectronicelectronicInventory に追加し、その結果を updatedElectronicInventory に保存します

以下の出力を表示してください:

  • updatedBookInventory の長さを出力します
  • updatedBookInventory[1].details.title を出力します
  • updatedBookInventory[1].details.author を出力します
  • updatedElectronicInventory の長さを出力します
  • updatedElectronicInventory[1].details.brand を出力します
  • updatedElectronicInventory[1].details.model を出力します
  • updatedElectronicInventory[0].id を出力します
  • updatedElectronicInventory[1].quantity を出力します

自分で試してみよう

// 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);

Introduction To TypeScriptのすべてのレッスン

自分で練習してみよう: JavaScriptオンラインコンパイラ