Current section: TypeScript 59 exercises
solution

Default Props

Loading solution

Transcript

00:00 All right, so we're going to say that the left default to 0, the right will also default to 0, and then the operator will default to plus. That is our goal. Those are the default values that we want. We're getting errors on all of these because right now, the props are not defaulted.

00:18 So let's make these optional. First, from a types perspective. So left can be optional, the operator is optional, right is optional. With that now, we're getting an error in here because it's saying, hey, you're trying to grab operations or grab undefined off of operations, because the operator can now be the key of

00:38 the type of operations or undefined because we just made it optional. In fact, the left can also be undefined and the right can also be undefined because they're optional. So here's how we're going to handle the defaults there. We'll say this is whatever left is or it's 0.

00:56 The operator is whatever the operator is set to or plus. You notice we have such a narrow type on there that we can get some autocomplete here, which is cool. Then our right can default to 0 also. With that, we're no longer getting any type errors of any kind, and we're getting the proper output.

01:14 So here we said the operator is the only thing we get left and right is going to be 0. On this first one, we just did left and right. We didn't do an operator, that operator showed up. Then we did the right as a default and we did the left as a default. I wonder what would happen if we do the right as a default.

01:33 Dividing by 0, oh my gosh. At least the world didn't explode. So the way that you do this is just add a little question mark right next to the property you want to make a optional. Then you don't necessarily have to do a default every time you do this. In our case, we need to have a value for those,

01:52 but having an undefined or unspecified value is totally a legit thing that you can do in certain scenarios. So yeah, there may be a case where it actually makes sense to not have a default value for these. But in our case, all of these should have default values.

02:10 I think you could probably argue that a calculator shouldn't have a default operator. That's funny, but we're just taking this to the extreme so that you can learn how to do optional properties and default values, which is something that you do in React components quite a lot.

02:30 So hopefully that was fun.