関数:在庫にアイテムを追加する
CoddyのJavaScriptジャーニー「Introduction To TypeScript」セクションの一部。レッスン 64/73。
チャレンジ
簡単前回のチャレンジから、以下の内容が提供されています:
- プロパティ
id、quantity、detailsを持つジェネリックインターフェースInventoryItem<T> - 3つの在庫アイテム:
bookItem、electronicItem、clothingItem
既存の在庫配列に新しいアイテムを追加する、addItem という名前のジェネリック関数を作成してください。
この関数は以下の要件を満たす必要があります:
- ジェネリック型パラメータ
Tを使用すること InventoryItem<T>[]型のパラメータinventoryを受け取ることInventoryItem<T>型のパラメータnewItemを受け取ること- 既存のすべてのアイテムに新しいアイテムを加えた、
InventoryItem<T>[]型の新しい配列を返すこと - 明示的な戻り値の型注釈を持つこと
以下の配列を作成し、関数をテストしてください:
bookItemのみを含む配列としてbookInventoryを作成します- 以下の内容を持つ
InventoryItem<{ title: string; author: string }>型のnewBookを作成します:id: 4quantity: 2details: { title: "Advanced TypeScript", author: "Jane Smith" }
addItemを使用してnewBookをbookInventoryに追加し、その結果をupdatedBookInventoryに保存します
electronicItemのみを含む配列としてelectronicInventoryを作成します- 以下の内容を持つ
InventoryItem<{ brand: string; model: string }>型のnewElectronicを作成します:id: 5quantity: 1details: { brand: "GadgetCorp", model: "Z500" }
addItemを使用してnewElectronicをelectronicInventoryに追加し、その結果を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のすべてのレッスン
2基本の型
基本の型: str, num, boolean'any' 型: 脱出ハッチ'unknown' 型'null' と 'undef' の扱い型推論の実践明示的な型アノテーションまとめ:基本の型の演習5型:エイリアス、ユニオン型、インターセクション型
プリミティブ型の型エイリアスユニオン型 ('|')ユニオン型の扱い方リテラル型インターセクション型 ('&')型エイリアスの組み合わせまとめ:高度な型の組み合わせ自分で練習してみよう: JavaScriptオンラインコンパイラ