optional properties samples incorrect if width: 0
due to if(0) being interpreted as false, the optional properties samples checking if(config.width) parameter will fail if a 0 value is supplied:
interface SquareConfig {
color?: string;
width?: number;
}
function createSquare(config: SquareConfig): {color: string; area: number} {
var newSquare = {color: "white", area: 100};
if (config.color) {
newSquare.color = config.color;
}
if (config.width) {
newSquare.area = config.width * config.width;
}
return newSquare;
}
var mySquare = createSquare({color: "black"});
console.log(mySquare.area);//100
mySquare = createSquare({color:"black", width:0});
console.log(mySquare.area); //100
mySquare = createSquare({color:"black", width:1});
console.log(mySquare.area); //1
I'm not the original author of the code, so I don't know if it was their intent - but it would be fairly nonsensical for a square to have a nameless color ("") or a zero area. It might be fair to keep it this way but leave an explanation.
Alternatively, we could use a different example entirely.
Similarly, the current example will treat "" and null identically for lastname. I think it's worth mentioning that in lots of other cases you will want to test explicitly for equality with undefined.