Unions and Narrowing 28 exercises
Problem

Conditional Narrowing in TypeScript

Here we have a function called validateUsername that takes in either a string or null, and will always return a boolean:

function validateUsername(username: string | null): boolean {
  return username.length > 5; // red squiggly line under `username`

  return false;
}

Te

Loading exercise

Transcript

00:00 In this exercise, we have a couple of things going wrong. We have a validate username function here where we can pass in either string or null and it's going to always return boolean. We've added a return type to make sure it does. Now, what we can see is in the tests here, if we pass in some strings here, then it should basically check to see if the username length is more than five.

00:20 And if it is, then like with Matt1234, then it should return true. But Alice, because it's five or less, it should be false. And Bob, because it's less than five, it should also be false. But how about for if it's null? What if we pass in null there? Well, this is the test that's failing.

00:38 And currently we're getting a runtime error because we're passing in null. But actually username here is possibly null. And we're actually causing a runtime error by trying to access a property of null. So I would like you to rewrite this function to make this error go away. I just want you to mess about with the code that's inside this block here. And you'll probably need to use some sort

00:59 of if statement and do a little bit of narrowing to make it go away, to make the test pass and to make this type error go away. So good luck.