Essential Types And Notations 20 exercises

Add an Array to an Object

Consider the following shopping cart code:

type ShoppingCart = {
userId: string;
const processCart = (cart: ShoppingCart) => {
// Do something with the cart in here
userId: "user123",
items: ["item1", "item2", "item3"], // squiggly line under `items`

Loading exercise


00:00 In this exercise, we have a function called ProcessCart and it takes in a cart which is of type ShoppingCart. Type alias ShoppingCart is right at the top here and currently it's got a user ID of string on it. But our ProcessCart function down the bottom, we're calling it with a user ID, but also with these items here.

00:18 And these items are an array of items or rather an array of strings. And so we need to find some way inside this ShoppingCart type at the top to basically represent an array of strings.

00:32 Because if we just have items string like this, it's not going to work because it's going to say type string array is not assignable to type string. So that is your challenge to try to figure out a type for the items here so that we can make this type error go away. And when we're implementing our ProcessCart function, it's all going to work. Good luck.