logoalt Hacker News

teaearlgraycoldtoday at 9:06 AM4 repliesview on HN

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?


Replies

sally_glancetoday at 9:19 AM

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.

show 1 reply
ravtoday at 12:07 PM

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...

show 1 reply
sargunvtoday at 9:14 AM

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

show 1 reply