Cart design
- TypeScript course
- Beginner
- Lesson 71/89
- 5 min
Design cart and product types and write the skeleton.
Product and Cart types
We define three core types for a shopping cart. Product represents a product (id, name, price). CartItem pairs a product with a quantity. Cart holds an array of items.
interface Product { id: string; name: string; price: number; }
interface CartItem { product: Product; quantity: number; }
interface Cart { items: CartItem[]; }Empty cart skeleton
To create an empty cart, you define a Cart object whose items field is an empty array. This is the initial state of the cart; it gets filled later by adding products.
const emptyCart: Cart = { items: [] };
console.log(emptyCart.items.length); // 0Practice Write the cart skeleton
Define a Product interface: id: string, name: string, price: number. Define a CartItem interface: product: Product, quantity: number. Define a Cart interface: items: CartItem[]. Create an empty cart and print the number of items.
Starter code
// Product arayüzü: id, name, price (hepsi string veya number)
// CartItem arayüzü: product ve quantity
// Cart arayüzü: items alanı CartItem dizisi
// emptyCart oluştur (boş sepet)
// öğe sayısını yazdırSample solution
interface Product {
id: string;
name: string;
price: number;
}
interface CartItem {
product: Product;
quantity: number;
}
interface Cart {
items: CartItem[];
}
const emptyCart: Cart = { items: [] };
console.log(emptyCart.items.length);Expected output
0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What information should a CartItem contain?
- Product and quantity Correct answer
- Only the product name
- Only the price
- Only the quantity
Explanation: A CartItem contains a Product and a quantity; this way we know which product and how many of it.
2 Complete the CartItem field
interface CartItem { product: Product; ____: number; }
interface CartItem { product: Product; quantity: number; }
Explanation: A CartItem contains a Product and a quantity. count, amount, and size are alternative names, but using quantity is the consistent TypeScript design.
3 Cart type parts
| Term | Meaning |
|---|---|
Product |
Product details (id, name, price) |
CartItem |
Product and quantity |
Cart |
Array of cart items |
items: CartItem[] |
Cart contents |