Menu
CoddyTech

Создание специфического типа инвентаря

Часть раздела Введение в TypeScript путешествия по JavaScript на Coddy. Урок 66 из 73.

challenge icon

Задание

Легко

Вам предоставлены следующие элементы из предыдущего задания:

  • Универсальный интерфейс InventoryItem<T> со свойствами id, quantity и details
  • Универсальная функция addItem, которая добавляет элементы в массивы инвентаря
  • Универсальная функция findItemById, которая ищет элементы по ID

Создайте два конкретных типа объектов и соответствующие им псевдонимы типов элементов инвентаря:

  • Создайте псевдоним типа Book со свойствами:
    • title типа string
    • author типа string
  • Создайте псевдоним типа Electronic со свойствами:
    • brand типа string
    • model типа string

Создайте псевдонимы типов для конкретных элементов инвентаря:

  • Создайте BookItem как InventoryItem<Book>
  • Создайте ElectronicItem как InventoryItem<Electronic>

Создайте конкретные элементы инвентаря, используя ваши новые псевдонимы типов:

  • Создайте specificBook типа BookItem с:
    • id: 100
    • quantity: 8
    • details: { title: "Clean Code", author: "Robert Martin" }
  • Создайте specificElectronic типа ElectronicItem с:
    • id: 200
    • quantity: 4
    • details: { brand: "Sony", model: "WH-1000XM4" }

Создайте типизированные массивы инвентаря:

  • Создайте bookStore типа BookItem[], содержащий specificBook
  • Создайте electronicStore типа ElectronicItem[], содержащий specificElectronic

Создайте дополнительные элементы и протестируйте вашу систему типов:

  • Создайте anotherBook типа BookItem с:
    • id: 101
    • quantity: 3
    • details: { title: "Design Patterns", author: "Gang of Four" }
  • Используйте addItem, чтобы добавить anotherBook в bookStore, и сохраните результат в expandedBookStore

Выведите следующие данные:

  • Выведите specificBook.details.title
  • Выведите specificBook.details.author
  • Выведите specificElectronic.details.brand
  • Выведите specificElectronic.details.model
  • Выведите длину expandedBookStore
  • Используйте findItemById, чтобы найти элемент с ID 101 в expandedBookStore, и выведите details.title результата
  • Используйте findItemById, чтобы найти элемент с ID 200 в electronicStore, и выведите quantity результата
  • Выведите expandedBookStore[1].details.author

Попробуйте сами

// Generic interface from previous challenge
interface InventoryItem<T> {
  id: number;
  quantity: number;
  details: T;
}

// Generic function from previous challenge
function addItem<T>(inventory: InventoryItem<T>[], item: InventoryItem<T>): InventoryItem<T>[] {
  return [...inventory, item];
}

// Create the generic findItemById function
function findItemById<T>(inventory: InventoryItem<T>[], id: number): InventoryItem<T> | undefined {
  return inventory.find(item => item.id === id);
}

// Create test inventories
const mixedBookInventory: InventoryItem<{ title: string; author: string }>[] = [
  { id: 10, quantity: 3, details: { title: "JavaScript Basics", author: "Alice Brown" } },
  { id: 11, quantity: 7, details: { title: "React Fundamentals", author: "Bob Wilson" } },
  { id: 12, quantity: 2, details: { title: "Node.js Guide", author: "Carol Davis" } }
];

const mixedElectronicInventory: InventoryItem<{ brand: string; model: string }>[] = [
  { id: 20, quantity: 5, details: { brand: "Samsung", model: "Galaxy S23" } },
  { id: 21, quantity: 1, details: { brand: "Apple", model: "iPhone 15" } }
];

// Test the function and print outputs
const result1 = findItemById(mixedBookInventory, 11);
console.log(result1 ? result1.details.title : undefined);

const result2 = findItemById(mixedElectronicInventory, 20);
console.log(result2 ? result2.details.brand : undefined);

const result3 = findItemById(mixedBookInventory, 99);
console.log(result3);

const result4 = findItemById(mixedBookInventory, 12);
console.log(result4 ? result4.quantity : undefined);

const result5 = findItemById(mixedElectronicInventory, 21);
console.log(result5 ? result5.details.model : undefined);

const result6 = findItemById(mixedBookInventory, 10);
console.log(result6 ? result6.id : undefined);

const result7 = findItemById(mixedElectronicInventory, 50);
console.log(result7);

Все уроки раздела Введение в TypeScript

Потренируйтесь самостоятельно: Песочница TypeScript