Check out a free preview of the full Intermediate React Native course:
The "TypeScript Solution" Lesson is part of the full, Intermediate React Native course featured in this preview video. Here's what you'd learn in this lesson:

Kadi walks through the solution to the TypeScript exercise.

Get Unlimited Access Now

Transcript from the "TypeScript Solution" Lesson

>> All right, let's see how to implement this pet type. So we already have a name, which is a string. Now let's look at the second type, so we have kind, which can be a cat, a dog, or a fish. So I could do kind is a string, because they're all string elements.

[00:00:16] However, we can actually be more strict here because if I needed a string, I could type whatever here and it would still be valid. So, let's use the old type and call it a cat or a fish. Or a dog. Now this means if you get different kinds of pets introduced, you'll need to add it to the coins.

[00:00:41] Next up we have an age, so we got 10, 2 and 1 so we can see that the age is a number. Now I got a favorite foods. So we have an array of strings, an array of one string and an array of a string, so let's do favorite foods.

[00:01:03] Let's make it a string, all right Next up we have a function for speak, so this just console logs something in this console log something and this doesn't have the speak function. So let's do speak, and let's make it an error function and then they get return void.

[00:01:27] Okay, so it works here, but here on the fish. We don't have a speak function, so we need to make this optional. So let's add a question mark before the colon, and now it's an optional type. And lastly we have an owner, so an owner is an object with two properties.

[00:01:49] So we can easily add an object here called owner, and we'll make this into an object, and we'll do name, string and age, none of that. You could also pull this out into a separate type, so you could do type owner equals and then copy the name and the age here.

[00:02:25] And in our pet type, we can reference this own type instead. And for example if this owner was an array, so if we had multiple owners, you could add an array in the end. So this is how you can combine types.