AzLearn

تمرين إعادة البناء

Inventory Search

أعد كتابة بحث مخزون TypeScript يستخدم generics ومفاتيح typed.

typescript ~16 دقيقة متوسط
أعد بناء الكود Rebuild

هذا هو الكود. اكتبه بنفسك.

الكود المرجعي
interface InventoryItem {
  sku: string;
  name: string;
  category: "book" | "course" | "tool";
  stock: number;
}

function findByKey<T, K extends keyof T>(items: T[], key: K, value: T[K]): T | undefined {
  return items.find((item) => item[key] === value);
}

function inStock(items: InventoryItem[]): InventoryItem[] {
  return items.filter((item) => item.stock > 0);
}

const inventory: InventoryItem[] = [
  { sku: "TS-BOOK", name: "TypeScript Notes", category: "book", stock: 4 },
  { sku: "GO-COURSE", name: "Go Course", category: "course", stock: 0 },
  { sku: "CLI-TOOL", name: "Practice CLI", category: "tool", stock: 12 },
];

console.log(findByKey(inventory, "sku", "CLI-TOOL"));
console.log(inStock(inventory).map((item) => item.name));
اكتب هنا