Unions and Narrowing 28 exercises
solution

Introducing Union Types in TypeScript

In order to fix this error, we'll introduce a new TypeScript concept.

A union type can be created by using the vertical bar character | between the types you want to combine.

In this case, we'll update the username parameter to be a union type by adding | null after string:



Loading solution

Transcript

00:00 Okay, in order to do this we're going to introduce a whole new character that we've not used before and a whole new concept. This is a union type. You create one of these little vertical bars after string and then this basically operates like an or character saying either

00:16 string or null. So this means then that whatever we pass in here has to be either a string or it has to be null. This or operator is core to how a lot of TypeScript magic works

00:33 really because we need to be able to represent different possibilities in our system. Because here we can see that getUsername now, if we hover over getUsername here or the username variable inside there, then it's typed a string or null. But magically, once we've checked

00:48 that it's not null, we can see that if we hover over username inside the template literal there, it's actually typed as string. Fascinating. We will explore the ramifications of this later. But it means, of course, if we hover over getUsername now, we can see that username can either be called with string or it can be called with null or it can be called with

01:08 a type that's string or null, which is kind of the thing that we're getting back from our database.