Let's extend the example using TypeScript's strong typing features.
First, we'll define interfaces for the user, cart, and cart items.
Then, we'll create a user object that compositionally connects to the shopping cart.
// Define the structure for a cart item
interface CartItem {
productId: number;
quantity: number;
}
// Define the structure for a user cart
interface UserCart {
userId: string;
items: CartItem[];
}
// Define the structure for a user
interface User {
id: string;
name: string;
email: string;
cart: UserCart;
}
// Create a user object that includes the cart
const user: User = {
id: 'user123',
name: 'John Doe',
email: 'john.doe@example.com',
cart: {
userId: 'user123',
items: [
{ productId: 1, quantity: 2 },
{ productId: 3, quantity: 1 }
]
}
};
console.log(user);
In this example:
We've defined interfaces for CartItem, UserCart, and User. The User interface compositionally includes a UserCart. We've created a user object that adheres to the User interface and includes the cart data. This approach ensures that our data structures are strongly typed, making it easier to catch potential type-related issues at compile-time.