Course contentsShow
← TypeScript
Lesson 301 of 1,7967. ObjectsFree lesson

Type Safety with Optional Properties

Understand how TypeScript narrows optional properties and requires undefined checks before use.

Type Safety with Optional Properties

You'll learn how TypeScript forces you to handle potentially missing properties safely before using them.

The Core Problem

When you mark a property as optional with ?, TypeScript knows that property might be undefined at runtime. This creates a type union behind the scenes: the property's type becomes Type | undefined.

Here's the crucial part: TypeScript won't let you access methods or perform operations on optional properties until you prove the value exists. This prevents the classic "Cannot read property of undefined" runtime error.

How TypeScript Protects You

type User = {
  name: string;
  age?: number;  // Really means: number | undefined
};

const user: User = { name: "Alice" };

// ❌ Error: Object is possibly 'undefined'
const nextYear = user.age + 1;

// ✅ Correct: Check first
if (user.age !== undefined) {
  const nextYear = user.age + 1;  // TypeScript knows age is number here
}

// ✅ Also works: Truthiness check
if (user.age) {
  const nextYear = user.age + 1;
}

Why This Matters

Think of optional properties like a box that might be empty. TypeScript forces you to open the box and check before using what's inside. You can't just assume it's there.

The type system narrows number | undefined down to just number inside your safety check, giving you full access to number operations.

type Product = {
  name: string;
  discount?: number;
};

function getPrice(product: Product): number {
  const basePrice = 100;
  
  // Must handle the undefined case
  return product.discount 
    ? basePrice - product.discount 
    : basePrice;
}

Key Takeaway: Optional properties create Type | undefined unions, and TypeScript requires explicit checks (narrowing) before you can safely use the value.