Hacker News new | ask | show | jobs
by spankalee 793 days ago
Yeah, classes are generally better than branded types for objects (unless you're just building discriminated unions).

What's particularly better these days is that you get nominal typing and brand checks with standard private fields:

    class Foo {
      #brand;

      static isFoo(o): o is Foo {
        return #brand in o;
      }
    }
3 comments

I don’t quite see why you’d need to brand simple objects at all! Just give them meaningful field names.

Branding primitives is useful because you don’t otherwise have a name that you can control (e.g. feet versus meters as was suggested elsewhere in this thread, both of which would have type “number”).

The article starts with the example of two different object types with field “x: number”. In that situation you should be branding the field, not the object! If the field has the same name and the same branded type, structural typing is correct for that object shape.

Is this different/better than using `instanceof`?
This is really neat, thank you for sharing!