Skip to main content

Define Optional Object Properties in TypeScript

· One min read

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; // highlight-line
}

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