4 ms·
Yeah, classes are generally better than branded types for objects (unless you're just building discriminated unions). What's particularly better these days is
by spankalee 3y 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;
}
}
- superamadeus 3y agoThis is really neat, thank you for sharing!
- iainmerrick 3y agoI 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.
- mbwgh 3y agoIs this different/better than using `instanceof`?