As a newcomer to TypeScript, I am currently exploring the documentation and came across an example in the "Optional Properties" section that caught my attention:
interface SquareConfig {
color?: string;
width?: number;
}
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" });
I grasp the concept of optional properties, but what puzzled me was the
: { color: string; area: number }
within the function arguments. Is this for type checking against the variables color
and area
? If so, why not define them outside the function and perform type checking like so:
let color:string;
let area: number;
Can someone please clarify what the purpose of this code snippet is?