You are here: Home / Topics / Optional Property interface typescript

Optional Property interface typescript

Filed under: TypeScript on 2024-03-18 11:50:20

In TypeScript, you can define optional properties in an interface by appending a question mark (?) to the property name. This allows you to specify that a property is not required to be present in objects that implement the interface.


Example 3: Optional Property
index.ts:
interface Person {
   name: string;
   age?: number;

   email?: string;
}
class Manager implements Person {
   name: string;
   constructor(name: string) {
       this.name = name;
   }
   disp() {
       return 'Hi, ' + this.name;
   }
}
console.log(new Manager('John').disp());
function printPerson(person: Person) {
   console.log(`Name: ${person.name}`);
   if (person.age) {
       console.log(`Age: ${person.age}`);
   }
   if (person.email) {
       console.log(`Email: ${person.email}`);
   }
}
const john: Person = {
   name: 'John',
   age: 30,
};
const jane: Person = {
   name: 'Jane',
   email: 'jane@example.com',
};
printPerson(john);
printPerson(jane);

About Author:
J
Java Developer     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.