Optional properties in interfaces allow some properties to be optional when defining the structure of an object. This means that those properties may or may not be present when creating an object.

In TypeScript, you can mark a property as optional by adding a ? after the property name.

Example: Optional Properties

interface SquareConfig {
  color?: string;  // Optional property
  width?: number;  // Optional property
}
 
function createSquare(config: SquareConfig): { color: string; area: number } {
  let newSquare = { color: "white", area: 100 };
 
  if (config.color) {
    newSquare.color = config.color;
  }
 
  if (config.width) {
    newSquare.area = config.width * config.width;
  }
 
  return newSquare;
}
 
let mySquare = createSquare({ color: "black" });
console.log(mySquare);  // { color: 'black', area: 100 }

Key Points:

  1. Optional properties are defined with a ? after the property name (color?: string and width?: number).
  2. When creating an object based on this interface, you don’t have to provide values for optional properties. They are allowed to be undefined.
  3. In the function createSquare, we check if the optional properties exist using if (config.color) and if (config.width) before using them.

Explanation:

  • color? and width? are optional properties in the SquareConfig interface. You can pass them, but they are not required.
  • The function createSquare checks whether color and width are provided. If they are, it updates the square’s properties.
  • If you provide only the color (like { color: "black" }), the function will still work and use the default area of 100 for the square.

Summary:

  • Use the ? symbol to mark properties as optional in interfaces.
  • Optional properties are useful when not all values are required for every object instance.