Current section: TypeScript 59 exercises
solution

Narrow Types

Loading solution

Transcript

00:00 All right, we're going to try the exponentiation operator here and we should get an error, but we're not. If I save this, the application blows up. So let's come up here and let's limit the operator to only these specific strings. So we're going to use union. It can be plus or minus

00:19 or multiply or divide. And with that now, we no longer have an error here because TypeScript knows, so I know what the operations is. It's these things. I know what the operator could possibly be. It's only those things and that matches up. So we don't have an error here anymore. And down here, we do get an error for that, which is nice. So if I get rid of that

00:39 and change that back to plus, then we get our application working exactly as we want. So we are doing swimmingly. So this is maybe not the most efficient way to do this. We're going to talk about that here in a second, but it does solve our immediate problem.

00:55 And if we were to take this a little bit further, which we will, then we can make the experience even better for us. But as far as the users of our components are concerned, this is a really nice experience. In fact, we even get some autocomplete now. Look at that. Oh, snap,

01:13 because we have a limited subset. We've narrowed the possible values. And so our editor can say, hey, here are the possible values you can enter, which I think is pretty stellar. So good job.