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);