Function to Find an Item by ID
Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 65 of 73.
Challenge
EasyYou are provided with the following from the previous challenge:
- The generic interface
InventoryItem<T>with propertiesid,quantity, anddetails - The generic function
addItemthat adds items to inventory arrays - Various inventory items and updated inventory arrays
Create a generic function named findItemById that searches for an item in an inventory array by its ID.
The function should:
- Use a generic type parameter
T - Accept a parameter
inventoryof typeInventoryItem<T>[] - Accept a parameter
idof typenumber - Return the found item of type
InventoryItem<T>orundefinedif not found - Have an explicit return type annotation of
InventoryItem<T> | undefined
Create test inventories:
- Create
mixedBookInventoryas an array containing:- An item with
id: 10,quantity: 3,details: { title: "JavaScript Basics", author: "Alice Brown" } - An item with
id: 11,quantity: 7,details: { title: "React Fundamentals", author: "Bob Wilson" } - An item with
id: 12,quantity: 2,details: { title: "Node.js Guide", author: "Carol Davis" }
- An item with
- Create
mixedElectronicInventoryas an array containing:- An item with
id: 20,quantity: 5,details: { brand: "Samsung", model: "Galaxy S23" } - An item with
id: 21,quantity: 1,details: { brand: "Apple", model: "iPhone 15" }
- An item with
Test your function and print the following outputs:
- Find item with ID 11 in
mixedBookInventoryand print the result'sdetails.title(orundefinedif not found) - Find item with ID 20 in
mixedElectronicInventoryand print the result'sdetails.brand(orundefinedif not found) - Find item with ID 99 in
mixedBookInventoryand print the result (should beundefined) - Find item with ID 12 in
mixedBookInventoryand print the result'squantity(orundefinedif not found) - Find item with ID 21 in
mixedElectronicInventoryand print the result'sdetails.model(orundefinedif not found) - Find item with ID 10 in
mixedBookInventoryand print the result'sid(orundefinedif not found) - Find item with ID 50 in
mixedElectronicInventoryand print the result (should beundefined)
Try it yourself
// Generic interface from previous challenge
interface InventoryItem<T> {
id: number;
quantity: number;
details: T;
}
// Items from previous challenge
const bookItem: InventoryItem<{ title: string; author: string }> = {
id: 1,
quantity: 5,
details: { title: "TypeScript Handbook", author: "John Doe" }
};
const electronicItem: InventoryItem<{ brand: string; model: string }> = {
id: 2,
quantity: 3,
details: { brand: "TechCorp", model: "X100" }
};
const clothingItem: InventoryItem<{ size: string; color: string }> = {
id: 3,
quantity: 10,
details: { size: "M", color: "Blue" }
};
// Generic function to add item to inventory
function addItem<T>(inventory: InventoryItem<T>[], newItem: InventoryItem<T>): InventoryItem<T>[] {
return [...inventory, newItem];
}
// Create book inventory and new book
const bookInventory = [bookItem];
const newBook: InventoryItem<{ title: string; author: string }> = {
id: 4,
quantity: 2,
details: { title: "Advanced TypeScript", author: "Jane Smith" }
};
const updatedBookInventory = addItem(bookInventory, newBook);
// Create electronic inventory and new electronic
const electronicInventory = [electronicItem];
const newElectronic: InventoryItem<{ brand: string; model: string }> = {
id: 5,
quantity: 1,
details: { brand: "GadgetCorp", model: "Z500" }
};
const updatedElectronicInventory = addItem(electronicInventory, newElectronic);
// Print outputs
console.log(updatedBookInventory.length);
console.log(updatedBookInventory[1].details.title);
console.log(updatedBookInventory[1].details.author);
console.log(updatedElectronicInventory.length);
console.log(updatedElectronicInventory[1].details.brand);
console.log(updatedElectronicInventory[1].details.model);
console.log(updatedElectronicInventory[0].id);
console.log(updatedElectronicInventory[1].quantity);All lessons in Introduction To TypeScript
1Getting Started with TS
What is TypeScript?Why Use TypeScript?Your First TypeScript CodeCompilation Process & ErrorsRecap: Introduction to TS4Working with Functions
Typing Params & Return ValuesTyping Arrow FunctionsThe 'void' Return TypeOptional Parameters with '?'Default Parameter ValuesTyping Rest ParametersDefining Function TypesRecap: Building Typed Funcs7Project: A Simple Task List
Project: Defining Task StructFunction to Add a Task10Project: Inventory Management
Project: Generic Inventory IteFunction: Add Items to Inv2Core Types
Basic Types: str, num, booleanThe 'any' Type: Escape HatchThe 'unknown' TypeWorking with 'null' & 'undef'Type Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Types: Aliases, Unions & Inter
Type Aliases for PrimitivesUnion Types ('|')Working with Union TypesLiteral TypesIntersection Types ('&')Combining Type AliasesRecap: Advanced Type Combos3Data Structure: Arrays & Tuple
Typed Arrays'readonly' Modifier for ArraysWhat is a Tuple?Declaring and Accessing TuplesDestructuring TuplesReadonly TuplesMulti-dimensional Typed Arrays Spread Operator with ArraysRecap: Arrays and Tuples