3 ms·
I’m mostly sitting this out, but I’ll interject here because this is wrong. Union types are often used as an XOR (a | b as “either a or b, but not both”), but t
by eyelidlessness 4y ago
I’m mostly sitting this out, but I’ll interject here because this is wrong. Union types are often used as an XOR (a | b as “either a or b, but not both”), but they’re an inclusive OR (Partial<a> & Partial<b>, as “some parts of a or b, the parts they share guaranteed”) which is almost never what anyone wants when dealing with objects. The pain is that you can’t distinguish them without a narrowing factor, and if you can’t the types are horridly complex.
- colejohnson66 4y agoI mean, that makes sense. If types `A` and `B` both have a function `doStuff`, is it bad to be able to do `x.doStuff()` without narrowing? For example: every object’s prototype chain ends with `Object.prototype`, so all objects have a `toString` function. I shouldn’t be forced to narrow my `number|bigint|string` (for example) just to do `x.toString()`. If I was, we’d get this ugly and bloated mess: function callToString(x: number | bigint | string) { if (typeof x === "number") x.toString(); else if (typeof x === "bigint") x.toString(); else x.toString(); } Regardless, they’re just copying JavaScript’s duck typing feature. It’s not much different than languages like Java and C# that have interfaces. In C#, if my parameter is IClonable, I don’t care what it is, but know there’s a `Clone()` method attached to it.