Unions and Narrowing 29 exercises
explainer

Narrowing Unions with `typeof`

Narrowing is one of TypeScript's most powerful features.

In this example, we have a convertTime function that takes in a parameter of time, that is either a string or a number.

Notice the if statement that uses the typeof operator to see if time is a string:


const co

Loading explainer

Transcript

00:00 Now that we know about union types, it's time to introduce one of TypeScript's most powerful features, and that's narrowing. So here we have a convert time function, and the convert time function takes in a parameter of time, which is string or number, and we have an if statement here. The if statement checks if type of time is string,

00:18 and if it is, then it console logs it, but you can imagine something else happening in here. If it's not type of string, then it still console logs it, and then it console logs it one more time. And if you think about this, if we call it with number, then this is going to resolve to false,

00:36 which means inside this little bracket here, this little scope, TypeScript knows that this is never going to be a number, right? Inside there, it's never gonna be a number. So if we hover over that, it's typed as string. TypeScript knows too that if this resolves to be true,

00:54 this kind of type of time equals string, if that resolves to be true, then in the else clause, it's going to be false. So that means that it's going to be number instead. And then right at the end of this, because we're not like returning or doing anything inside here, then this time at the end is going to be still string or number

01:13 because we've outside of this sort of narrowing scope. So you can think of here as these scopes as being really important in TypeScript when it comes to narrowing things down. If we add something else to this union, let's say we add a Boolean there, for instance, now time is going to be still string, right?

01:32 Because it's still checking if type of time equals string, but inside here, it's going to be number or Boolean. If we add an else if and say type of time equals number, for instance, then it will be checked there and it will be number. Otherwise, we'll go else console.log time again,

01:50 and now time is going to be Boolean. Isn't this so, so powerful? And aren't your brain cells just sort of sparking with all the cool things you can do here? Type of is just one way that you can narrow down unions and narrow down all the different possibilities. And we're going to be looking at a bunch of different ways

02:09 in the remainder of this section.