Course contentsShow
← TypeScript
Lesson 199 of 1,7965. Type Narrowing FundamentalsFree lesson

Truthiness Narrowing Basics

How TypeScript narrows types based on truthiness checks like if (value) for null and undefined elimination.

Truthiness Narrowing Basics

What you'll learn: How TypeScript automatically eliminates null and undefined from a type when you use truthiness checks.

The Core Idea

In JavaScript, values like null, undefined, 0, "", false, and NaN are "falsy" — they behave like false in conditions. TypeScript is smart enough to understand that when you write if (value), you're checking whether something exists. If the condition passes, TypeScript narrows the type by removing null and undefined from the possibilities.

Think of it like a security checkpoint: "If you made it past this if gate, you can't be null or undefined anymore."

How It Works

When you have a variable that might be null or undefined, TypeScript won't let you use it safely. But after a truthiness check, TypeScript knows the variable has a real value:

function greet(name: string | null) {
  // Here, name could be string OR null
  
  if (name) {
    // Inside here, TypeScript knows name is string
    // null is eliminated because it's falsy
    console.log(name.toUpperCase());
  }
}

The same works with undefined:

let age: number | undefined = getUserAge();

if (age) {
  // TypeScript knows age is number here
  console.log(age + 1);
}

Important Caveat

Truthiness narrowing only removes null and undefined. It doesn't help with other falsy values like 0 or "", which are valid values of their types.

Key Takeaway: TypeScript narrows types inside if (value) blocks by eliminating null and undefined, because those values are falsy and won't pass the condition.