Create Specific Inventory Type
Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 66 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 - The generic function
findItemByIdthat searches for items by ID
Create two specific object types and their corresponding inventory item type aliases:
- Create a type alias
Bookwith properties:titleof typestringauthorof typestring
- Create a type alias
Electronicwith properties:brandof typestringmodelof typestring
Create type aliases for specific inventory items:
- Create
BookItemasInventoryItem<Book> - Create
ElectronicItemasInventoryItem<Electronic>
Create concrete inventory items using your new type aliases:
- Create
specificBookof typeBookItemwith:id: 100quantity: 8details: { title: "Clean Code", author: "Robert Martin" }
- Create
specificElectronicof typeElectronicItemwith:id: 200quantity: 4details: { brand: "Sony", model: "WH-1000XM4" }
Create typed inventory arrays:
- Create
bookStoreof typeBookItem[]containingspecificBook - Create
electronicStoreof typeElectronicItem[]containingspecificElectronic
Create additional items and test your type system:
- Create
anotherBookof typeBookItemwith:id: 101quantity: 3details: { title: "Design Patterns", author: "Gang of Four" }
- Use
addItemto addanotherBooktobookStoreand store inexpandedBookStore
Print the following outputs:
- Print
specificBook.details.title - Print
specificBook.details.author - Print
specificElectronic.details.brand - Print
specificElectronic.details.model - Print the length of
expandedBookStore - Use
findItemByIdto find item with ID 101 inexpandedBookStoreand print the result'sdetails.title - Use
findItemByIdto find item with ID 200 inelectronicStoreand print the result'squantity - Print
expandedBookStore[1].details.author
Try it yourself
// 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);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