Essential Types And Notations 20 exercises
solution

Representing an Array of Objects

As it happens, there are a few different ways to express an array of objects. Some of these solutions are nicer than others, but all of them work.

Creating an Intermediate Type

The primary approach would be to to create a new Ingredient type that we can use to represent the objects in the arr

Loading solution

Transcript

00:00 So I've written down four possible ways of expressing this. Let's look at, I think, the nicest way first, or my preferred way. So the sort of obvious way to do this, if you're thinking in terms of types here, is we have a type of recipe. Let's also think about a type for ingredients. That makes sense, doesn't it?

00:18 So we could say type ingredient equals nameString and quantityString2. And now when we go into the recipe here and add our ingredients, let's say ingredients, and we can say ingredientArray, an array of ingredients.

00:35 This reads really, really nicely and we get a sort of sense of our domain model here. We're building up a sense of the language that we're using for each type. This is really pretty. And now all of our errors have gone away. We can see that recipe is referenced by name here, which is lovely too. And it's just all working nicely.

00:53 If we reference, let's say, recipe.ingredients, let's take the first one, and we've got name and quantity available to us there. You can start to see how we can represent really complex types in TypeScript. There's a couple of other solutions here too. So we've got, again, sorry, I've switched the order here, type ingredients is now at the top,

01:12 and we're using the array syntax instead of the square bracket syntax. The third instruction here is this version, is we just declare it in line. There's no reason you can't specify these square brackets on an inline object literal. So this is sort of works perfectly fine too.

01:31 It's quite nice that TypeScript lets you do either the clean version or this messy version, which is quite nice for prototyping. And then finally, we've got this version too, which is where we have the array with the angle bracket syntax, which is you're basically, instead of passing string to it, which we've

01:48 seen before, you're passing the entire object literal to it. So many, many different options here. I'm not sure kind of which one is the best. I'd probably say that this one using the type ingredients and then specifying it with the square brackets is the best, but that's my personal preference.

02:04 And it is always nice to have your type segregated like this, but sometimes you'll want to just inline that object literal and that's fine too.