Backbencher.dev

Define Optional Object Properties in TypeScript

Last updated on 8 Feb, 2023

We can mark a particular property in an object as optional in TypeScript.

Consider following JavaScript object:

const person = {
  name: "Joby",
  isMarried: true,
  spouseName: "Ninu",
};

The property spouseName should be optional. Only if isMarried is true, spouseName has relevance.

We can mark a property as optional by adding a question mark after the property name. Here is how the interface of person looks like:

interface Person {
  name: string;
  isMarried: boolean;
  spouseName?: string;}

The optional question mark can also be used for class properties and function parameters.

--- ○ ---
Joby Joseph
Web Architect