Optional properties in interfaces allow some properties to be optional when defining the structure of an object. This means that those properties may or may not be present when creating an object.
In TypeScript, you can mark a property as optional by adding a ?
after the property name.
Example: Optional Properties
interface SquareConfig {
color?: string; // Optional property
width?: number; // Optional property
}
function createSquare(config: SquareConfig): { color: string; area: number } {
let newSquare = { color: "white", area: 100 };
if (config.color) {
newSquare.color = config.color;
}
if (config.width) {
newSquare.area = config.width * config.width;
}
return newSquare;
}
let mySquare = createSquare({ color: "black" });
console.log(mySquare); // { color: 'black', area: 100 }
Key Points:
- Optional properties are defined with a
?
after the property name (color?: string
andwidth?: number
). - When creating an object based on this interface, you don’t have to provide values for optional properties. They are allowed to be
undefined
. - In the function
createSquare
, we check if the optional properties exist usingif (config.color)
andif (config.width)
before using them.
Explanation:
color?
andwidth?
are optional properties in theSquareConfig
interface. You can pass them, but they are not required.- The function
createSquare
checks whethercolor
andwidth
are provided. If they are, it updates the square’s properties. - If you provide only the
color
(like{ color: "black" }
), the function will still work and use the defaultarea
of100
for the square.
Summary:
- Use the
?
symbol to mark properties as optional in interfaces. - Optional properties are useful when not all values are required for every object instance.