Optional Object Properties

What

Optional object properties are fields that may or may not be present on an object instance.

How

You mark a property as optional by adding a question mark (?) after the key name in the type definition:

type Superhero = {
  name: string;
  strength: number;
  cape?: boolean; // Optional property
};

Why

Optional properties allow you to model data structures where certain fields are only relevant in specific contexts. In TypeScript, an optional property’s type is automatically unioned with undefined (e.g., boolean | undefined), which ensures you handle the missing state safely in your code.

Summary

Use optional properties to define flexible schemas, but avoid overusing them to ensure your code remains predictable.