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

Optional Properties vs Index Signatures

Understanding the difference between optional known properties and index signature values, including undefined handling.

Optional Properties vs Index Signatures

What you'll learn: How optional properties and index signatures differ in their type safety guarantees, especially when it comes to undefined handling.

The Core Difference

Both optional properties and index signatures allow for "missing" values in objects, but they behave very differently when you access them:

Optional properties (prop?: Type) mean the property may or may not exist, but if it does exist, it has a specific type. When you access it, TypeScript knows it could be undefined.

Index signatures ([key: string]: Type) mean any key is valid, and accessing any property always returns the value type directly—TypeScript doesn't automatically add undefined to the type, even though the property might not exist at runtime!

Type Safety Comparison

type WithOptional = {
  name?: string;
};

type WithIndex = {
  [key: string]: string;
};

const obj1: WithOptional = {};
const result1 = obj1.name;  // Type: string | undefined ✓

const obj2: WithIndex = {};
const result2 = obj2.name;  // Type: string (not undefined!) ⚠️

Notice the problem: result2 is typed as string, but at runtime it's actually undefined! The index signature doesn't protect you from accessing missing keys.

Combining Both

You can mix known optional properties with an index signature:

type Config = {
  timeout?: number;
  [key: string]: string | number | undefined;
};

The index signature must be compatible with all known properties, including the undefined from optional ones.

Key Takeaway: Optional properties give you undefined in the type automatically for safety; index signatures do not—any key access returns the value type directly, creating a runtime/compile-time mismatch you must handle manually.