Comment by sargunv
5 days ago
Even with strict flags on, there are failures. A trivial example:
function mutateArray(
arr: (string | number)[]
) {
arr.push(1);
}
const a: string[] = ["one", "two"];
mutateArray(a);
a is now a string[] with a number inside
Woah, that's quite an issue. The equivalent code in Python doesn't typecheck, since `list` is invariant and hence list[str] doesn't fit list[str|int]. Unusual for TS to handle types worse than Python.
Very interesting. I’m shocked the typescript creators built a system with this failure mode. I guess the solution here is to have tsc change the type of “a” after the call to mutateArray, unless the arr argument is marked as readonly.
Is there a name for this failure mode?
I think the problem is the union argument type - intuitively we read "array of strings OR numbers", but actually it means "array of strings AND numbers". Probably generics would be more appropriate here, with the type param constrained to string or number. Then tsc would also complain about pushing a number without checking the item type before.
If it's an "array of strings AND numbers", then it should not be allowed to call the function with a string[], because those are different types.
5 replies →
In TypeScript it's called "bivariance", which sounds very programming language theory like, but is not a term typically used in academic contexts, since it is unsound almost by default. It's described here: https://www.typescriptlang.org/docs/handbook/type-compatibil...
Key sentence in their justification seems to be:
"allowing this enables many common JavaScript patterns"
Honestly at this point they should make a new strict "no js" mode, as the ecosystem likely has reached a tipping point where you can get by without mixing typed and untyped js at compile time. Wonder if targeting wasm directly would help ensure those boundaries are ensured...
1 reply →
I'm not aware of a name, but I'm also curious if there is one because I had a hard time searching for it.
I came across it on ThePrimeagen's YouTube channel: https://youtu.be/u1WmiqlrqL0
I asked an LLM and it described the problem as "covariant typing of mutable collections" or "unsound covariance". I'm not mathematically educated in this area but that sounds right?
1 reply →
Yikes. I've only been using ts for about a year, I had no idea this was considered a "valid" case. Seems like a type error to me. I wonder how they justify this?