3 ms·
I generally agree with everything you're saying, after extensive use of Typescript. Its safety guarantees usually only help within extremely tight bounds, and t
by quaunaut 5y ago
I generally agree with everything you're saying, after extensive use of Typescript. Its safety guarantees usually only help within extremely tight bounds, and there's surprisingly little that it catches that couldn't be inferred directly.
However, a question:
> Arrays are covariant in their type param, so I can pass a `Dog[]` into a function that accepts `Animal[]`. If that function adds a `Cat` to the passed array, the compiler is perfectly happy, but we'll see a runtime error.
I don't think this one is true anymore, assuming you type it correctly. I've provided an example[1].
---
Separately however, I think it's worth noting that I've been playing with the idea of doing a project in plain Javascript again, to see if I feel any serious productivity losses.
- [1]: https://www.typescriptlang.org/play?#code/C4TwDgpgBAwghsKBeKBvAUFKpIC4oDk8wBANJlAK4DOE1AMgJbDAQBOARgPYAe+3XADYQ4AO3QBfdOhzQAIlwDmyNBVn4CCxWQoALLjQgc2XANYRR+YG0oRJ02VACCoxgFs4glVqgAfWAjSAPQAVCGYIVAAKrqM1FBcotBsEMCUbKLxYlAABi7ungDaALo52OAQAHQRQegAxonUiHAAJi3UxACSogBm7CktKgAUYgWC1Pj5HoIlAJTIAHyqWKPT1JVgNLpDqOqExGRUtAzMrJy8VjYQErMUKWkZUKue1Pah4VCRMXEJSVD36UyUAA7roEBAAG7scqQKAgAxQRRwKFQZikJ7xQSJZRweLMKAQHisUTtXJTTw5SrOeLwyhQOrZWgQdH4-pcNjxYBgxD41qkhmIDgQBmGVGICGMITgzm6aANTLWOCMUSILg9J5QaiUDiyaqfWryppPNodBAAUSJFlJKAAPFECZaSfFyYIFiNXGt8FE5otlk8PS8NlsdnsiAhDoYTix2Nw+Ngrjc7qlAf6xq8pPVGogWkoJlAtCUVIVdhUNFpDvpDMYzBZLrYJMVMwqoD0uFwVHzTcBun02AMhjnFNRbobBXA2B2TcQLcT2gPc7cgA https://www.typescriptlang.org/play?#code/C4TwDgpgBAwghsKBeK...
- 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.