Re:TypeScript is terrible for library developers
by nicoburns on Tuesday August 23, 2022 @03:59PM
(#32570633)
Luckily these types are not complex at all to type in Typescript. You just enumerate all the options with a | character separating them.
[ Parent
| on HN ]
Re:TypeScript is terrible for library developers
by 323 on Tuesday August 23, 2022 @04:03PM
(#32570679)
Right, 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.
Re:TypeScript is terrible for library developers
by isbvhodnvemrwvn on Wednesday August 24, 2022 @03:21AM
(#32575922)
Which is why you can have aliases for those types, each level of abstraction can be nicely wrapped up. It just describes the reality.
Re:TypeScript is terrible for library developers
by eyelidlessness on Tuesday August 23, 2022 @10:03PM
(#32574178)
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.
Re:TypeScript is terrible for library developers
by colejohnson66 on Tuesday August 23, 2022 @11:49PM
(#32574775)
I 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.