CodeWithMihir

TypeScript Tutorial

TypeScript Truthiness Narrowing Explained

Learn how truthiness narrowing works in TypeScript, including null checks, undefined checks, empty strings, optional values, and common mistakes.

Welcome back! I am Mihir, and in this lesson we will learn truthiness narrowing in TypeScript.

Truthiness narrowing happens when TypeScript narrows a type based on whether a value is treated as true or false in an if condition.


Basic Truthiness Narrowing

function printName(name: string | null) {
  if (name) {
    console.log(name.toUpperCase());
  }
}

Inside the if block, TypeScript knows name is not null.


Checking undefined

function greet(name?: string) {
  if (name) {
    return `Hello, ${name}`;
  }

  return "Hello, guest";
}

Because name is optional, its type is:

string | undefined

The if (name) check narrows it to string.


Falsy Values

JavaScript treats these values as falsy:

  • false
  • 0
  • ""
  • null
  • undefined
  • NaN

This matters because truthiness checks can remove more than just null or undefined.


Common Mistake with Empty Strings

function formatTitle(title: string | null) {
  if (title) {
    return title.toUpperCase();
  }

  return "Untitled";
}

This treats an empty string as missing.

formatTitle("");

The result is:

"Untitled"

That might not be what you want.


Safer Null Check

If you only want to remove null, check for null directly.

function formatTitle(title: string | null) {
  if (title !== null) {
    return title.toUpperCase();
  }

  return "Untitled";
}

Now an empty string is still treated as a real string.


Checking null and undefined Together

function printValue(value: string | null | undefined) {
  if (value != null) {
    console.log(value.toUpperCase());
  }
}

value != null removes both null and undefined.

This is one place where loose inequality is intentionally useful.


Truthiness with Arrays

function printFirst(items: string[] | undefined) {
  if (items) {
    console.log(items[0]);
  }
}

This checks whether items exists, but it does not check whether the array has elements.

Better:

function printFirst(items: string[] | undefined) {
  if (items && items.length > 0) {
    console.log(items[0]);
  }
}

Quick Recap

  • Truthiness narrowing uses conditions like if (value).
  • It is useful for removing null and undefined.
  • Be careful with falsy values like "" and 0.
  • Use direct checks when you need exact behavior.
  • value != null removes both null and undefined.

Next up, we will continue with Equality Narrowing →.