
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:
- TypeScript: Using Variables to Set Object Keys
- Using Rest Parameters in TypeScript Functions
- TypeScript: Function with Optional and Default Parameters
- Calculate Variance and Standard Deviation in Javascript
- TypeScript: Intersection Type Examples
You can also check out our TypeScript category page for the latest tutorials and examples.