develwoutacause’s avatardevelwoutacause’s Twitter Archive—№ 947

      1. Just shot myself in the foot today because #TypeScript enums start at 0, which is falsey. That means that if (someEnumOrUndefined) {} won't work the way you expect. I'm wondering if: enum Foo { Bar = 1, Baz, } Should be a best practice? typescriptlang.org/play?target=7#code/KYOwrgtgBAYg9nKBvAUFdUBCBDATgGigHoioBeKABigCMBPKAE2ADNswAbAFzQxwC9CJclACMtBszaceAXxQoAxnBABnLrTwAuWAigAfKGBBSAliGCMR8OADocuANwpTLKAAoaeAJRRlauA5gWw44AHN3AHIvXChgAA9TdVVI70diUgAROGBVEEiNAAdccy5bBX91TX4dGwMjE1ZzS2sEe2x+Z1cPL35fSsDg0IjojrjE5NT04QAFEpAuVXKgA
    1. …in reply to @develwoutacause
      This seems to have come up before in the @typescript repo but was dismissed because truthy/falsey behavior is occasionally useful and other languages have the same hazard. They suggest that the 0 value should be the "Zero like" or "unspecified" value. github.com/microsoft/TypeScript/issues/7473
  1. …in reply to @develwoutacause
    @typescript I can agree with some of the specific points, but I don't see them as a compelling argument. Not every enum has a "Zero like" value and this is a very easy mistake to make with a complex "rethink the way you are designing enums" solution that most devs won't think of up front.
    1. …in reply to @develwoutacause
      I honestly feel that defaulting enums to 1 is a pretty clean solution here. Advanced usages which have a "Zero like" value or use it as a boolean can explicitly set = 0, basic usages won't have this foot-gun.
      1. …in reply to @develwoutacause
        Migrating existing code would definitely be the toughest aspect. It's actually pretty mechanical since a schematic or codemod could just add = 1 to all existing enums in a codebase, though #TypeScript doesn't really have that upgrade story, so I get the churn issue.
        1. …in reply to @develwoutacause
          The other solution would be to disallow if (x as number) {}, since this is really an issue with 0 falsiness than anything with enums. I would personally be ok with that too, though I think people would likely push back on that even more strongly.