TypeScript: Object with Optional Properties

Updated: April 10, 2022 By: Pennywise Post a comment

In TypeScript, you can specify that some or all properties of an object are optional. To do so, just add a question mark (?) after the property name.

Example:

interface Person {
  email: string; // this property is required
  name?: string; // this property is optional
  phone?: string; // this property is optional
}

// this person doesn't have name and phone number
const person1: Person = {
  email: '[email protected]',
}

// this person doesn't have phone number
const person2: Person = {
  email: '[email protected]',
  name: 'Just A Man',
}

// this person have name and phone number
const person3: Person = {
  email: '[email protected]',
  name: 'Red',
  phone: '123 456 689'
}

// this function print information of a person
function printInfo(person: Person) {
  console.log('Email:', person.email);

  if (person.name) {
    console.log('Name:', person.name);
  } 

  if (person.phone) {
    console.log('Phone number:', person.phone);
  }
}

printInfo(person1);
printInfo(person2);
printInfo(person3);

Output:

Email: u1@u090812

Email: [email protected]
Name: Just A Man

Email: [email protected]
Name: Red
Phone number: 123 456 689

Further reading:

You can also check out our TypeScript category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles