4 ms·
> I don't think this one is true anymore, assuming you type it correctly. I've provided an example[1]. You are correct that using a generic does fix the issue.
by ragnese 5y ago
> I don't think this one is true anymore, assuming you type it correctly. I've provided an example[1].
You are correct that using a generic does fix the issue. But you called that "correct". But why, as a code author, should it be my responsibility to understand type theory better than my compiler? Because, according to basic type theory (to the extend that I understand it), TypeScript is allowing an operation that is literally incorrect in the first example. (mutable) Array types must be invariant in the type parameter. It should bitch at us for both examples.
And this won't happen with just arrays. It'll happen if you do the same thing with an object with a field. E.g., instead of `Animal[]`, we could have the function take a `{ pet: Animal }`, and pass it a `{ pet: Dog }`, and replace the Dog with a Cat, causing a runtime error for the poor schmoe who thought he still had a Dog.