Function to Get Item Details
Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 67 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 - Type aliases
Book,Electronic,BookItem, andElectronicItem - Inventory arrays
bookStoreandelectronicStore
Create a function named getItemDetails that takes an InventoryItem<any> and uses type guards to determine what type of item it is, then prints appropriate information.
The function should:
- Accept a parameter
itemof typeInventoryItem<any> - Use the
inoperator to check ifitem.detailshas atitleproperty - Use the
inoperator to check ifitem.detailshas abrandproperty - Print
"Book: [title] by [author]"if it's a book - Print
"Electronic: [brand] [model]"if it's an electronic - Print
"Unknown item type"if it's neither - Have a return type of
void
Create test items:
- Create
testBookof typeInventoryItem<any>with:id: 300quantity: 6details: { title: "TypeScript Handbook", author: "Microsoft Team" }
- Create
testElectronicof typeInventoryItem<any>with:id: 400quantity: 2details: { brand: "Dell", model: "XPS 13" }
- Create
unknownItemof typeInventoryItem<any>with:id: 500quantity: 1details: { color: "Red", size: "Large" }
Test your function by calling getItemDetails with each test item:
- Call
getItemDetails(testBook) - Call
getItemDetails(testElectronic) - Call
getItemDetails(unknownItem)
Also test with items from your existing stores:
- Use findItemById to find item with ID 100 in expandedBookStore, then call getItemDetails with the result
- Use findItemById to find item with ID 200 in electronicStore, then call getItemDetails with the result
Try it yourself
// Generic interface from previous challenge
interface InventoryItem<T> {
id: number;
quantity: number;
details: T;
}
// Generic functions from previous challenge
function addItem<T>(inventory: InventoryItem<T>[], item: InventoryItem<T>): InventoryItem<T>[] {
return [...inventory, item];
}
function findItemById<T>(inventory: InventoryItem<T>[], id: number): InventoryItem<T> | undefined {
return inventory.find(item => item.id === id);
}
// Create specific object types
type Book = {
title: string;
author: string;
};
type Electronic = {
brand: string;
model: string;
};
// Create type aliases for specific inventory items
type BookItem = InventoryItem<Book>;
type ElectronicItem = InventoryItem<Electronic>;
// Create concrete inventory items
const specificBook: BookItem = {
id: 100,
quantity: 8,
details: { title: "Clean Code", author: "Robert Martin" }
};
const specificElectronic: ElectronicItem = {
id: 200,
quantity: 4,
details: { brand: "Sony", model: "WH-1000XM4" }
};
// Create typed inventory arrays
const bookStore: BookItem[] = [specificBook];
const electronicStore: ElectronicItem[] = [specificElectronic];
// Create additional items and test type system
const anotherBook: BookItem = {
id: 101,
quantity: 3,
details: { title: "Design Patterns", author: "Gang of Four" }
};
const expandedBookStore = addItem(bookStore, anotherBook);
// Print outputs
console.log(specificBook.details.title);
console.log(specificBook.details.author);
console.log(specificElectronic.details.brand);
console.log(specificElectronic.details.model);
console.log(expandedBookStore.length);
console.log(findItemById(expandedBookStore, 101)!.details.title);
console.log(findItemById(electronicStore, 200)!.quantity);
console.log(expandedBookStore[1].details.author);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