TypeScript Fundamentals TypeScript Fundamentals

Challenge 4: Functional Cashier

Check out a free preview of the full TypeScript Fundamentals course:
The "Challenge 4: Functional Cashier" Lesson is part of the full, TypeScript Fundamentals course featured in this preview video. Here's what you'd learn in this lesson:

In this challenge, students build out a functional shopping cart. Mike takes questions from students.

Get Unlimited Access Now

Transcript from the "Challenge 4: Functional Cashier" Lesson

>> Mike North: So we're going to build a functional cashier. So this is gonna illustrate the power of functions and closures and give us a little bit more practice around interfaces, and types, and how they play with functions. So what we wanna do is we can invoke a function called cashier and this should be stabbed out in the starting point for the exercise.

[00:00:27] And whatever value we capture there, it's gonna have sort of an API on it that we can use to add things to a shopping cart. So you can see we can add one apple. Note that we're not passing a third parameter there. So sort of, unless you specify quantity as we did when we are adding pears, the assumption is, just add one to my cart.

[00:00:48] We should also be able to add an item in that following way. Right, where we're passing an object of that particular structure. When I say structure, you should be thinking interface, maybe. And then, finally, the cart.length and cart.total properties, I advise you use a getter there. So that when we access that property value, you can sort of iterate over your array of items and you can figure out how many items you have or how much your total bill is.

[00:01:17] Keep in mind, I'm sorry that I did not get this into the slide, and I just realized there's ambiguity. In terms of the count of items, we would regard it as how many individual things are in your cart, not how many types of items are in your cart.

[00:01:33] So, two pairs count as two items. So when you're returning cart.length, in this case it would be two plus three plus one is six. Makes sense? All right, I gave you some shapes to use as the basis for designing your interfaces. So items that can be added to the cart should look kind of like this.

[00:01:57] And an object that is returned by the cashier function, and add, and addItem, it should look like this, right? And the reason we return it from add and addItem is so that, as demonstrated by this slide here, we should be able to kind of just keep chaining .add, .add, .add.

[00:02:17] If you’ve used promises before, .then, .then, same concept. So you wanna kinda keep returning the same API so that you can chain, and chain, and chain.