Optional Interface Properties in TypeScript
The interface can also specify special optional properties. They are needed so as not to limit the object to a certain set of properties. In this case, the use of properties that are not included in the interface is prohibited. Optional properties are specified using the ? operator, specified after the property name.
Let's create an interface IFigure that defines properties for all figure objects. Let color be an optional property:
interface IFigure {
height: number;
width: number;
color?: string;
}
Now let's create a rectangle object and print its color value to the console:
let rectangle: IFigure = {
height: 200,
width: 300,
color: 'red'
}
console.log(rectangle.color); // 'red'
Now let's check if there will be an error if we don't set the color in the object:
let rectangle: IFigure = {
height: 200,
width: 300
}
console.log(rectangle.color);
There will be no error and a message will be displayed in the console stating that the color is simply not defined:
undefined
Make an interface IDate for an object storing a date: year, month and day. Let all properties of the object be optional.