Menu
CoddyTech

Crear un tipo de inventario específico

Parte de la sección Introducción a TypeScript del Journey de JavaScript de Coddy. Lección 66 de 73.

challenge icon

Desafío

Fácil

Se te proporciona lo siguiente del desafío anterior:

  • La interfaz genérica InventoryItem<T> con las propiedades id, quantity y details
  • La función genérica addItem que añade elementos a los arreglos de inventario
  • La función genérica findItemById que busca elementos por ID

Crea dos tipos de objetos específicos y sus correspondientes alias de tipo para elementos de inventario:

  • Crea un alias de tipo Book con las propiedades:
    • title de tipo string
    • author de tipo string
  • Crea un alias de tipo Electronic con las propiedades:
    • brand de tipo string
    • model de tipo string

Crea alias de tipo para elementos de inventario específicos:

  • Crea BookItem como InventoryItem<Book>
  • Crea ElectronicItem como InventoryItem<Electronic>

Crea elementos de inventario concretos utilizando tus nuevos alias de tipo:

  • Crea specificBook de tipo BookItem con:
    • id: 100
    • quantity: 8
    • details: { title: "Clean Code", author: "Robert Martin" }
  • Crea specificElectronic de tipo ElectronicItem con:
    • id: 200
    • quantity: 4
    • details: { brand: "Sony", model: "WH-1000XM4" }

Crea arreglos de inventario tipados:

  • Crea bookStore de tipo BookItem[] que contenga specificBook
  • Crea electronicStore de tipo ElectronicItem[] que contenga specificElectronic

Crea elementos adicionales y prueba tu sistema de tipos:

  • Crea anotherBook de tipo BookItem con:
    • id: 101
    • quantity: 3
    • details: { title: "Design Patterns", author: "Gang of Four" }
  • Usa addItem para añadir anotherBook a bookStore y almacénalo en expandedBookStore

Imprime las siguientes salidas:

  • Imprime specificBook.details.title
  • Imprime specificBook.details.author
  • Imprime specificElectronic.details.brand
  • Imprime specificElectronic.details.model
  • Imprime la longitud de expandedBookStore
  • Usa findItemById para buscar el elemento con ID 101 en expandedBookStore e imprime el details.title del resultado
  • Usa findItemById para buscar el elemento con ID 200 en electronicStore e imprime la quantity del resultado
  • Imprime expandedBookStore[1].details.author

Pruébalo tú mismo

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

Todas las lecciones de Introducción a TypeScript

Practica por tu cuenta: Playground de TypeScript