Unions and Narrowing 28 exercises

Narrowing with Boolean Won't Work

Consider this version of the validateUsername function, that isn't working as expected when using JavaScript's Boolean() function:

function validateUsername(username: string | null): boolean {
// Why isn't this working?
const isUsernameOK = Boolean(username);
if (isUsername

Loading explainer


00:00 There's a bit of a caveat here, which is when you're using the boolean function, which ships kind of in JavaScript, then it doesn't quite work as expected. We noticed before that we could do this sort of double bang to make this work, where we're basically sort of checking,

00:16 converting username into a boolean by doing this sort of like bang bang before it. Because if this one resolves to not username, and this one resolves to not not username, which converts it into a boolean and says whether it's truthy or falsy, but if we do the same thing by just applying it with a boolean operator, it doesn't work.

00:34 And that's because this is just a plain function. TypeScript is actually really good at understanding sort of operator syntax here by using OR and AND, it understands all those different combinations. But when you just use a plain boolean function here, it doesn't understand it because it just thinks of this as a boolean

00:53 and doesn't understand that it's related to username. So while TypeScript's narrowing is extremely powerful, it does have little gotchas like this, which we will run into occasionally, and I'll point out as we go.