3 ms·
I understand your reasoning. I think a case could be made that TypeScript shouldn't allow `readonly` as it's currently implemented on object types (though I als
by brundolf 5y ago
I understand your reasoning. I think a case could be made that TypeScript shouldn't allow `readonly` as it's currently implemented on object types (though I also think the opposite case could be made).
But here's the thing: at least in the real-world TypeScript code that I've written and seen over the years, `readonly` is usually not of crucial importance. It's a nice-to-have. I use it to remind myself "oh yeah, best not to mutate that in this section of the code". In most of those cases it's also obvious from context that we're working with the value immutably. Finally, I'm not usually mixing-and-matching mutable and immutable versions of the same type, which is where you're most likely to run into this problem. If a thing is readonly, it's probably readonly everywhere. I've had very few cases where it's "the world will blow up if this gets mutated in this one narrow situation which might accidentally happen because I passed an immutable value into a mutable argument".
That's all very hand-wavy and anecdotal. I acknowledge that. But if you want to make good technical decisions you have to weigh the tradeoffs, not just the principles, and the reality of any usable type system layered on top of JavaScript is going to be messy and have compromises. I've used Flow - which tends to be stricter about these things (to a general disregard for JavaScript's idioms and syntaxes) - and it's frankly horrible. We migrated a huge codebase at one point from Flow to TypeScript because it was simply not helping us be productive. The other alternative is to use a language designed from the get-go to support a perfect type system - which can be a great option in some scenarios - but that comes with its own trade-offs if you're targeting the web ecosystem, especially if you have an existing codebase in JavaScript. You're going to have a hard time porting a huge existing codebase to Elm, for example.
I personally believe that TypeScript is pretty darn close to a local optimum for "static type system that can be gradually applied to existing real-world JavaScript codebases".
Your individual complaints are not technically wrong, but you're taking a hyper black-and-white stance that purposely focuses on details that aren't as significant and ignores real-world tradeoffs. If you don't like TypeScript, don't use it! The rest of us will continue to enjoy and benefit from it.