3 ms·
Luckily these types are not complex at all to type in Typescript. You just enumerate all the options with a | character separating them.
by nicoburns 4y ago
Luckily these types are not complex at all to type in Typescript. You just enumerate all the options with a | character separating them.
- 323 4y agoRight, but people compose. They take this union and put it in another object, which also allows multiple types for some field, and then they take that object and put it in another one, and then you have a 10 line type declaration for 3 fields.
- isbvhodnvemrwvn 4y agoWhich is why you can have aliases for those types, each level of abstraction can be nicely wrapped up. It just describes the reality.
- deleted 4y ago[deleted]
- eyelidlessness 4y agoI’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.