microsoft / TypeScript-Handbook

Deprecated, please use the TypeScript-Website repo instead
https://github.com/microsoft/TypeScript-Website
Apache License 2.0
4.88k stars 1.13k forks source link

optional properties samples incorrect if width: 0 #178

Open petcarerx opened 8 years ago

petcarerx commented 8 years ago

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
DanielRosenwasser commented 8 years ago

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.

cmcaine commented 7 years ago

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.