TypeScript-Handbook icon indicating copy to clipboard operation
TypeScript-Handbook copied to clipboard

optional properties samples incorrect if width: 0

Open petcarerx opened this issue 10 years ago • 2 comments

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

petcarerx avatar Mar 07 '16 19:03 petcarerx

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.

DanielRosenwasser avatar Mar 07 '16 19:03 DanielRosenwasser

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.

cmcaine avatar Sep 29 '17 17:09 cmcaine