by ragnese · 5y ago · 0 comments
TypeScript's type system is so utterly broken that I honestly don't know if my code is ANY more robust than if I had written it in JavaScript.
Record<> is broken/unsound: https://github.com/microsoft/TypeScript/issues/45335
Generics are wonky and sometimes wrong: https://github.com/microsoft/TypeScript/issues/31006
The `readonly` keyword does absolutely nothing: https://github.com/microsoft/TypeScript/issues/13347
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.
TypeScript is actually so bad that it might have honestly made JavaScript worse, if that's even possible.
Calling it "broken" is complete hyperbole, and no, it's not "worse than Javascript". There's a reason why the entire ecosystem is switching to Typescript, and that's because it is extremely effective at helping teams manage complex stateful applications.
Its type system is quite broken and I'm not going to walk back on using that term. Sometimes the TypeScript designers/devs will explain that the brokenness is intentional. But some of the issues have nothing to do with JavaScript compatibility. For example, we all know about the conundrum of `type` vs `interface`, but did you know that an object-shaped `type` will automatically conform to a mapped type, but an `interface` wont? Playground: https://www.typescriptlang.org/play?ssl=20&ssc=1&pln=21&pc=1...
Or how about the fact that basic inheritance sub-typing doesn't work?: https://www.typescriptlang.org/play?#code/MYGwhgzhAECCB2BLAt...
Moreover TypeScript's type system is so powerful it actually catches a good number of bugs that Haskell would never catch, because it does control flow analysis by default. For many languages you would need to install a separate static analyser (if one even exists), having CFA as part of type checking in your editor is godlike.
Sure if you are writing software for a radiotherapy machine, don't write it in typescript! Use whatever proof assistant takes your fancy. But if bugs are not literally going to kill people, TypeScript's type system is about the best in existence.
If you enjoy your type system being more expressive at the cost of soundness, you should try this language called JavaScript! It lets you express things that you can't in TypeScript!
> Moreover TypeScript's type system is so powerful it actually catches a good number of bugs that Haskell would never catch, because it does control flow analysis by default. For many languages you would need to install a separate static analyser (if one even exists), having CFA as part of type checking in your editor is godlike.
The control flow analysis has nothing at all to do with the soundness of the type system. Kotlin has similar with it's "smart casting," but that doesn't require it to have an intentionally unsound type system.
And for your 'inheritance sub-typing' example, can you explain what the "right" behavior would be? It's a function that mutates properties on an object, how is the type system supposed to detect that? That's already a code smell and should be avoided.
Right. That one, by itself, won't introduce a bug. But it's just another weird thing to remember about TypeScript's type system being inconsistent. I bumped in to it because I wanted to define my own JSON-like type for use as query params being sent to a particular API that has a custom syntax for certain things (like passing an object as a query param, etc). So I wrote a type something like this:
type ExtendedJson = boolean | number | string | null | undefined | OurCustomTimestampType | SomeOtherCustomTypeWeUse | ExtendedJson[] | ExtendedJsonObject
type ExtendedJsonObject = Record<string, ExtendedJson>
And then in my function that sends requests to the API in question, I require a parameter like `queryParams?: ExtendedJsonObject`, and I have a function that knows exactly how to format this ExtendedJsonObject into the right string for the request. Neato.
Except then, I realized that most of the specific query types I wrote were interfaces. But I only got compile errors in some places and not others. I had no idea why some of my types worked and some didn't. The error message was clear enough, I guess. It said that the type didn't conform to `{ [string]: ExtendedJson }`, but I coudln't figure out why some of my types did conform and some didn't.
What's worse is that some of my query types that were defined as interfaces DID work without a compile error! In hindsight, I now understand that the reason those worked was because I was actually "wrapping" those interfaces into types with things like Readonly<FooQueryParams> or Omit<BarQueryParams, 'someKey'>. So those were now types instead of interfaces, but it wasn't an obvious enough clue for me, so I spent hours trying to figure it all out.
If that were the only weird thing, I wouldn't still be bitching about it, but in the last year that I've been focusing on this frontend project, I feel like I've spent countless hours learning about holes and inconsistencies in TypeScript. It feels like every single week I learn about some other broken or inconsistent nonsense that I just think I shouldn't have to deal with.
> And for your 'inheritance sub-typing' example, can you explain what the "right" behavior would be? It's a function that mutates properties on an object, how is the type system supposed to detect that? That's already a code smell and should be avoided.
The correct behavior is that it should be an error to pass a HasDog to a function that requires a HasAnimal. { pet: Dog } is NOT a sub-type of { pet: Animal } just because Dog is a sub-type of Animal. The type theory concept is called "variance". You have "covariant", "contravariant", and "invariant". Mutable object and array types are invariant in their field types. So you can't pass a Array<Dog> for an Array<Animal> because adding an Animal to an Array<Dog> is a type error: an Animal is not necessarily a Dog. However, you CAN pass an immutable Array<Dog> for an Array<Animal> because you are guaranteed to only be reading the elements as Animals, and a Dog is an Animal. Return types often have the inverse type relationships to input params: You can return an Array<Dog> for an Array<Animal> return type because the caller who receives the returned value will treat it as an Array<Animal>, so it's okay to add a Cat to it, even though it was originally only Dogs.
And, while I agree that mutating an input param is generally a bad idea, that's no excuse for the type system to not be correct. Every other statically typed language is going to handle this correctly (except primitive arrays in Java. They are also unsound, like TS, but, in Java's defense, it's only primitive arrays, and you almost never use arrays directly in Java- you use List<T>, which is not wrong/unsound). When I say every other statically typed language, I'm literally talking about every statically typed language I've ever used: C++, Java (again, except arrays), Go, Swift, Rust, Kotlin, Scala, even PHP. They all handle this correctly, because it's really basic type theory.
Well, when comparing it with strongly typed languages it does look broken for sure.
I once attended a talk where the speaker had identified half a dozen axes that papers or projects were calling "strong"/"weak" with relation to type systems. Some were not even consistent with themselves, switching definitions halfway.
Type systems are tools, whose formal properties can be described and analyzed in precise detail. Unfortunately, that kind of precision is hard, so semantically empty words like "strong" get used a lot instead. This message is intended to raise awareness about that fact.
Anyways most likely you do know well what I meant. JS vs C++ for example.
The proof is in the pudding. I've been writing JS (and a bunch of statically typed languages) for over twenty years. Large JS codebases have become possible now thanks to TypeScript (an example is VSCode). If you look at any large JS ecosystem project today, chances are that it's written in TypeScript rather than in vanilla JS. People are adopting it because they see benefits.
If you've used TypeScript over the years, you'll also see that many major releases catch a set of new bugs in "strict" mode (which used to successfully compile earlier). That's the team fixing some of the issues you mentioned.
I understand the point. I just don't think it's a good point. If you tell me that I have a type system, then I'd expect that I could actually lean on it to catch type errors, and I'd expect it's own language features (like `readonly`) to actually do what they claim they do. I would NOT expect someone to add `readonly` to their language, but have it not actually make something a `readonly` type.
> The proof is in the pudding. I've been writing JS (and a bunch of statically typed languages) for over twenty years. Large JS codebases have become possible now thanks to TypeScript (an example is VSCode). If you look at any large JS ecosystem project today, chances are that it's written in TypeScript rather than in vanilla JS. People are adopting it because they see benefits.
I don't buy the argument that something being popular means it's actually good. There's a lot of group-think that goes into things being adopted. Not to mention that it's a Microsoft product and they have zillions of dollars to make sure the editor tools are good, lots of popular JS libraries get TypeScript types added on top, and just plain old PR advertising.
And yes, the ability to gradually switch from JS to TS makes TS an easier choice for people who are already working with JS or who are used to JS. But, that doesn't mean that Flow, Elm, ReasonML, ReScript, ClojureScript, PureScript, etc, aren't actually better tools with bigger benefits. It just means that TS got the critical mass mindshare amongst JS devs, and now has the advantage of "everyone else is writing libraries for TS, so if I pick Flow for my project, I won't have as big an ecosystem to pull from."
To me, each of your examples of brokenness is completely outside the day-to-day which I work in (and honestly my comprehension vis a vis why you would use them), so I can't speak too much to them, but as someone who has gone from untyped JS (obviously) to strictly typing each key of each property in my program, I am finding it pretty funny to see you conclude
> TypeScript is actually so bad that it might have honestly made JavaScript worse
I couldn't disagree more. The quality of the programming, the ability to share the mental model more easily with others, the developer experience of autocomplete and declaration files; each of these things is an order of magnitude improved, and the emergent efficiency of individuals and teams follows suit.
Well, I literally said that I shit on Java all the time, so yeah... I hate most of Java, and my blood pressure goes up just thinking about the shitty null handling, lack of any concept of immutability, weak as hell type system, and the nightmarish combination of commonplace runtime reflection paired with type-erased generics.
> To me, each of your examples of brokenness is completely outside the day-to-day which I work in (and honestly my comprehension vis a vis why you would use them), so I can't speak too much to them, but as someone who has gone from untyped JS (obviously) to strictly typing each key of each property in my program, I am finding it pretty funny to see you conclude
It's not outside my day-to-day. I'm complaining because I'm being bitten by TypeScript's brokenness all the time. If you try to use the advanced TypeScript features, you'll hit all manner of inconsistencies and brokenness, too. I'm sure of it. And if you're only using the very simple typing, are you really doing anything that JSDoc wouldn't do for you?
I'm fairly convinced (and I don't mean this in a condescending way) that the main group of devs that really likes TypeScript must have done mostly JavaScript and/or Python before. Because I can't imagine that someone who has spent a couple of years doing C# or C++ or Rust or Swift or even Go would be comfortable with all of the holes in TypeScript's type system.
I don't think this is entirely wrong, it's exactly TypeScript's retained dynamic-ism that makes it familiar and "easier"; but in my case I've spent significant time writing Java, including production scheduling software, and I just fully disagree that TS is "weak as hell" and has "type-erased generics". Like I said, I find it in me to strictly type programs including the boundary-crossing data (GraphQL w/ codegen or io-ts are leaders in their respective paradigms) and including a library of generic components which correctly can give you access to any data T you passed through to implement content generators etc..
For example, there were complaints about Record<>, but I simply use the object syntax { [key: string]: number | string }, so I can't speak to your use case, but I don't really understand why Record would be used.
I suppose I agree immutability doesn't exist without explicit use of Object.freeze, but I can't believe I would hear someone say "shitty null handling" as a TS/JS complaint when they come from Java land. To reduce my implementations to "JSDoc" is pretty funny as well
For the example about generics, I suppose I'd have to understand why it was using `K extends keyof T` instead of `K in keyof T`, I would agree the "extends" keyword is horrible for generics but I also find it difficult to conceptualize why someone would care about the keys in the superset that aren't in the default set (i.e. K extends keyof T - K in keyof T seems like a useless set to me)
To conclude, I guess I would love to see you show me what you are using "advanced TypeScript features" for, because I write fairly complex dataflow / model / graph editors & capabilities, and go to lengths to provide the capabilities generically as a component library, and I've never found an issue providing type hints. Period. I of course haven't implemented everything ever though, and I do avoid doing too much in the world of union types, so maybe this is why
The biggest holes can be filled via compiler options, and most of the rest can be papered over with the right coding practices (use Maps instead of Records, lint against `any` and type-casting, etc).
I haven't encountered the situation you described, but you could probably solve it by making the function generic over TArray extends Animal[].
The rest of what you've said doesn't line up with my experience. TypeScript is an imperfect tool that requires some elbow-grease to fully benefit from. I would prefer a typed language that didn't have to work under its real-world constraints (but not Java, because of null-checking at the very least), but over the years it's caught more bugs for me than I could possibly hope to count.
There's no earthly reason that a `type` should automatically implement Record<string, unknown> and an `interface` shouldn't. That's just dumb and annoying- not necessarily "wrong". However, it's definitely wrong to allow me to pass `const o = {}` into a function that wants `Record<string, string>`. How in the world does TypeScript (with the strict flag set!) think that an empty object is able to return a string value for any arbitrary string key? That's absurd.
The issue I raised about arrays isn't just arrays, actually. It happens with object fields as well. See https://www.typescriptlang.org/play?#code/MYGwhgzhAECCB2BLAt...
And, the `readonly` keyword has nothing at all to do with JavaScript. Yet, they added this keyword that is completely and utterly useless. To the point that I actually introduced a bug in my own code because I put `readonly` and `Readonly<>` everywhere and expected it to actually help me. It did help me... most of the time. And then it didn't. Because it turns out that you can always take a Readonly value, assign it to a non-Readonly variable and then just mutate the hell out of it, and the compiler won't even bat an eye: https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgA...
That's just... so bad. I don't even know what else to say. Sure, it caught some of my mistakes, but if it won't even catch all of the class of errors that it's supposed to, then I have to basically be just as careful as if I didn't use the feature at all. So, it's not reducing my mental burden at all. If anything, it's just giving us/me a false sense of security and tricking me into thinking that I DON'T need to be as careful.
It's not. `Record<string, string>` doesn't mean it has a mapping for every string key (that's not possible), it means it might or might not have a mapping for any given string key; it really is analogous to a Map, and it's perfectly valid to pass an empty map to an argument that takes a map of a particular type. The only thing wrong with it is that `MyRecord[someKey]` will by default have type `string`, not type `string|undefined`. This it presumably to help with JS code that commonly indexes objects by strings without checking that the keys return values. Luckily, there's a compiler option to make it return `|undefined` (and it works on arrays too, which have the same problem by default): https://www.typescriptlang.org/tsconfig#noUncheckedIndexedAc...
> Because it turns out that you can always take a Readonly value, assign it to a non-Readonly variable and then just mutate the hell out of it
I am surprised and disappointed that this works without casting, but I think with casting it's reasonable. TypeScript has to give you trap-doors to work around its checks when they don't serve your purposes; this is part of the "being overlaid on an imperfect language" thing. The important thing is that those circumventions are explicit and stand out.
Though I will say, you definitely can't pass a readonly object/array to a non-readonly object/array function argument, so I'm doubly surprised your example works. I may dig into it further later just out of curiosity.
Yes, it absolutely does mean that. Just because you can't correctly implement an object that satisfies the type doesn't mean that the type means something else (`never` is also a type that you can't implement).
> The only thing wrong with it is that `MyRecord[someKey]` will by default have type `string`, not type `string|undefined`.
Um, yeah. That's what's wrong. And therefore Record<string, string> literally does mean a string value for every string key.
The problem here is that some of these "utility types" have a specific intention behind them, and you aren't "supposed to" use Record this way. You're "supposed to" give it more specific types, like Record<'a' | 'b', string>.
But the compiler should be smart enough to know that nothing can possibly satisfy Record<string, string>, so if you write the type, it should be impossible to assign to it.
> Luckily, there's a compiler option to make it return `|undefined` (and it works on arrays too, which have the same problem by default): https://www.typescriptlang.org/tsconfig#noUncheckedIndexedAc...
That's not the solution here, because it will cause a Record<'a' | 'b', string> to return string|undefined when I do `o['a']`, which is also wrong.
The solution is for TypeScript to handle Record correctly.
> I am surprised and disappointed that this works without casting, but I think with casting it's reasonable. TypeScript has to give you trap-doors to work around its checks when they don't serve your purposes; this is part of the "being overlaid on an imperfect language" thing. The important thing is that those circumventions are explicit and stand out.
I have no problem with casting. Having hard type casts does not make the language imperfect or incorrect.
> Though I will say, you definitely can't pass a readonly object/array to a non-readonly object/array function argument, so I'm doubly surprised your example works. I may dig into it further later just out of curiosity.
Definitely?
https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgA...
Definitely confusing. Perhaps poorly designed. But it's not type-theoretically incorrect. I'm complaining about TypeScript being literally incorrect in its handling of types. Not "strange" or "weird" or "surprising", but incorrect.
The same is true for Java arrays. I thought the Liskov substitution principle was tautological when I first heard about it, but it seems like the original designers of Java disagree. Another example (albeit from the standart library, not the typesystem itself) is that if you try to modify a `List` or similar collection, it may throw an `UnsupportedOperationException` because it's immutable - instead of having a superinterface with only non-mutating methods and only implementing that.
First point: Yes, Java's arrays are broken and it offends me greatly. However, in practice, it's much more common to use Lists, which are not broken. In JavaScript/TypeScript "Array" is the equivalent of Java's List, so if you want a dynamically sized, contiguous, collection, you are stuck with the broken thing.
Then, the other issue is that, despite my comment's wording, this problem isn't ONLY present in Arrays. It's also a problem with objects, and (I assume) every other non-primitive type. See here: https://www.typescriptlang.org/play?#code/MYGwhgzhAECCB2BLAt...
So even a basic object field is broken in TypeScript's type system. What the hell are we supposed to do with this?
I do have thoughts and opinions about Java's Collection interfaces, the immutable implementations, etc, but that feels like a whole other topic.
Flow handles some of these cases better, but the invisible keyboard of the market has decided that the extra conceptual/syntactical overhead of introducing co/contravariant types is not worth it for these corner cases. You may disagree, that’s fine. But I’d suggest treating the problem as the engineering tradeoff that it is rather than an absolute fact that every type system must not have any holes and those that do are worthless.
> rather than an absolute fact that every type system must not have any holes and those that do are worthless.
Also, don't straw man me, please.
This is an unfortunate relic of pre-1.5 Java. The rest of the Collection API types correctly. A type-safe generic alternative is Arrays::setAll.
> if you try to modify a `List` or similar collection, it may throw an `UnsupportedOperationException`
Again, an historical artifact. `List` is from Java 1.2, you would effectively have to deprecate List<T> for that to work.
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/C4TwDgpgBAwghsKBeK...
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.
You gave three examples that seem relatively rare. At work we use TypeScript to type a codebase that was mostly plain JavaScript, and we write TypeScript as plain JavaScript. It does very well its job of offering use better tooling and compile-time guarantees. If you consider it as a way to statically-type existing JS codebases, it's good. If you consider it as a language on its own, it's not great.
I gave a few more examples in other comments in this thread. I can go look at the code comments I wrote in my project and come up with a longer list for you if you like.
> You gave three examples that seem relatively rare. At work we use TypeScript to type a codebase that was mostly plain JavaScript, and we write TypeScript as plain JavaScript. It does very well its job of offering use better tooling and compile-time guarantees. If you consider it as a way to statically-type existing JS codebases, it's good. If you consider it as a language on its own, it's not great.
This is a legitimately genuine question: if you're treating TypeScript as just type annotations on an otherwise regular-old-JavaScript codebase, then why are you using TypeScript rather than just JavaScript with JSDoc comments?
Also, I can't quite tell. Are you defending TypeScript's brokenness by suggesting we just don't use all of its advertised features? Isn't that... kind of weak? It's like the joke about going to the doctor: "Doctor, my elbow hurts when I do this." "Well, don't do that!" -- If TypeScript advertises a feature, shouldn't that feature, like, actually work?
TypeScript is way easier to write, and allows to anotate more stuff. We do have some JS that will stays as JS that's anotated with JSDoc, and it's a worse experience than TS.
> Also, I can't quite tell. Are you defending TypeScript's brokenness by suggesting we just don't use all of its advertised features?
I'm defending the usefulness of the tool, but not its marketing. I think the approach of trying to cover every single usage of JS is not the best, and leads to some complex features and weird edge cases like the ones you mentionned. But for typing plain JS, it works very well.
I guess we get a lot of value from TS because static typing is easy when your code wasn't that dynamic in the first place.
> If TypeScript advertises a feature, shouldn't that feature, like, actually work?
Fair point. I honestly don't know what a codebase that doesn't really benefits from TS looks like, but from your description I can see that their claims are a bit too much. I consider TS as part of a campaign from Microsoft trying to regain mindshare and/or control of developers, and thus always took their claims with a grain of salt.
Also, somehow, the tooling for it has one of the best features around(compiling to readable JS), but all other tooling is completely absent, and frankly, bad.
The problem is that function parameter variance is still wrong, even with all the strict flags. You just have to wrap the Dog/Animal in an Array or object. Pass in an { pet: Dog } to a function that accepts a { pet: Animal }, and the function can replace your Dog with a Cat, and TypeScript is perfectly happy to let you call `o.pet.bark()` afterwards.
It’s not an excuse because where possible I think TS should be stricter but I don’t think stuff like this really gets in the way of it providing me value when writing code.