5 ms·
The section on how union & intersection types behave with interfaces (rather than primitives) has them flipped: a union of interfaces will allow access to only
by comp_throw7 4y ago
The section on how union & intersection types behave with interfaces (rather than primitives) has them flipped: a union of interfaces will allow access to only the intersection of the fields/methods of all the types (unless you do the work to distinguish between which type you're working with), while an intersection will allow access to the union of the fields/methods of the composed types.
i.e. `ICat | IDog` will only allow `pet.eat()`, and `ICat & IDog` will allow `pet.eat()`, `pet.meow()`, and `pet.bark()`.
Good article otherwise, though. The explanation of top/bottom types was more intuitive than most attempts.
- ealexhudson 4y agoThat's incredibly interesting, because I've been using union types a while and didn't know this. I think a lot of people will get introduced to them via function signatures, and var: ICat | IDog not meaning "var could be an ICat or an IDog" is a bit unintuitive given the boolean math. But ultimately more useful? As in, code should never test whether this thing is an ICat or IDog, and I guess it's interesting that I don't remember ever encountering an issue where I attempted to access a member that was only present on one interface. Perhaps it would be too overloaded, but "ICat + IDog" instead of "ICat & IDog" feels more obvious, I suppose a better convention for "ICat | IDog" is difficult though. "ICat /\ IDog" for intersection and "ICat \/ IDog" for union doesn't roll off the tongue.
- bacro 4y agoI think ICat | IDog is perfect. It means exactly that, the value can be of type ICat _OR_ IDog, so in that sense, we can only access properties that are in both of them until we know for sure if we are dealing with a ICat or a IDog specifically.
- deleted 4y ago[deleted]
- hither_shores 4y ago"+" is probably a bad choice: sum types are a separate thing. In TypeScript, they can be implemented as Sum<X, Y> = { tag: "left", data: X } | { tag: "right", data: Y } Generally higher order types are named according to what they do to types, not terms. `x: ICat & IDog` means "x is in the intersection of ICat and IDog", not "x is the intersection of an ICat and an IDog". (The latter interpretation only even makes sense for record types and a few other special cases: what's the intersection of an integer and a string supposed to be?)
- allenp 4y agoFor anyone with trouble remembering/conceptualizing this - it follows the opposite convention as bitwise operators in javascript, so it is counter-intuitive. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_AND https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...