Unions and Narrowing 28 exercises

Handling Null Values in TypeScript

Here we have a function called getUsername that takes in a username string. If the username is not equal to null, we return a new interpolated string. Otherwise, we return "Guest":

function getUsername(username: string) {
if (username !== null) {
return `User: ${usern

Loading exercise


00:00 In this exercise, we have a function called getUserName and we're passing in getUserName. And what we're doing here is if the username is not equal to null, we return userUserName. Otherwise we just return guest. Now down the bottom here, we are expecting to be able to call getUserName either with

00:18 a string or with null. And this is currently not working. We're getting an error here saying argument of type null is not assignable to parameter of type string. Now you can imagine like we would probably never actually call this with a null value here.

00:34 But let's imagine it's like a property of a user that we're getting from the database. Well they might have a name or they might not depending on how they signed up. So we need to be able to handle nulls here. But currently this declaration of username only handles string. So this sort of check of null is sort of not really doing anything.

00:53 We need to change this definition, the username definition to be string or null. Good luck.