123 points · by ingve · 4y ago · 175 comments
This is exactly why it got so popular, and TypeScript support in the JS ecosystem is so good. It's easy to just strip the TS metadata and you're left with working JS. This is why projects like esbuild managed to ship TS support so quickly (without type-checking). Good luck doing that with a new language.
I for one am "all in" on TypeScript, with all its shortcomings it's just the best of both worlds, and so easy to get on board.
I'm not going to beat the dead horse of how unsound TypeScript's type system is. We all know that most of that is intentional because it would just be too inconvenient to work with existing JavaScript code (Aside: think about what this implies about existing JavaScript code. This makes alarm bells go off in my head).
However, why should I have to deal with an unsound type system in my new, fresh, TypeScript-only code?
I'm not saying it's simple or criticizing anybody's work, but it would VASTLY increase my opinion of TypeScript if I could enable some kind of 'truly-strict-new-code' flag that would error on unsound code in the current project and maybe just warn when I call unsound code from a dependency.
Because, honestly, I'm truly disappointed that the one language that finally has a chance to unseat JavaScript has such a poor type system that it can't even do basic sub-type variance correctly no matter how many flags you set. Out of all of the statically typed languages I've used, TypeScript has helped me the least when it comes to type errors.
I wish there was language that was basically JavaScript/TypeScript, but it gets rid of backwards-compatible JavaScript edge cases and conventions (like, no more undefined, no more {} == ‘0’, no more weird function ‘this’), removes advanced types and makes the type system sound, and (just in case) can actually check typecasts and non-null assertions at runtime. JavaScript and TypeScript are honestly great languages, but they are great languages with major flaws in the name of backwards-compatibility.
Even with strict typing enabled, I write a surprising amount of bugs which ultimately come down to type errors. And not only that but silent type errors, because TypeScript’s casts and not-null-assertions aren’t checked. So often I find that a mistyped or null value managed to slip through a type guard without the compiler saying anything.
And yes, I really wish that TypeScript's non-null assertions actually included a runtime check. Type casts can't really do anything at runtime without a definition of what "being type Foo" actually means, since the types are erased, but you can definitely check if something is null or undefined and throw an error.
I think it would be fair to have the non-null assertion do a runtime check, and if you want the non-null assertion with no runtime code, just use a type cast.
Surely preventing 99% of issues (or 90%, or 80%) is good?
I'm also not aware of too many real-world instances of unsoundness in TS that has caused problems. Obviously I don't know your specific scenario, but it's possible there are ways to work with TS (instead of against it) to get a good level of type safety.
You can’t assume there aren’t other trade-offs that you have to factor in to the analysis.
EDIT: I'm sorry. I thought you were someone else.
[REDACTED]
You would have a function like this:
parseJsonString : String -> Result Error Person
Where Result is a value that is either an Error or a Person.
To get the Person value out, the type system forces you to also do something with the Error if it exists. Not handling both possibilities in some way is a type error.
I mean, that's kind of the whole point of static typing, right?
If you're speaking to TypeScript/JavaScript, specifically, then yeah, the compiler can't guarantee anything because someone can hop into the running program and start modifying objects as they please (at least for web page code).
But the compiler could still make the weaker guarantee that "the code that I can see is soundly typed". And for 99% of us that's effectively the same thing.
If you correctly type the response of that request then the answer becomes yes again.
FWIW the lack of explicit variance annotations (and probably many other TS unsound design choices) are not so much related to supporting old untyped JS, but rather language design decisions that have to do with pragmatism and type system complexity.
I can't find it now but I have a vague recollection Hejlsberg talking about the explcit variance annotations explicitly, how those were a huge can of worms in C# and they didn't want to bring them to TS. Unlike Flow, by the way, which does have explicit variance handling and doesn't suffer from the beforementioned foot gun (but does have its own foot guns of course).
Personally, I hate the latter, but not as much as I hate unsoundness.
But, what I'm talking about is even more basic: https://www.typescriptlang.org/play?#code/MYGwhgzhAECCB2BLAt...
The code I wrote there is actually wrong for two reasons:
1. Type variance
2. Readonly doesn't do fuck-all in TypeScript for object types
Arguably no language in the world makes that distinction and Microsoft's "Just My Code" debugger tools are fantastic but use a lot of heuristics that you generally tell get as many false positives as false negatives, which is likely why it would always be a toggle.
That said, I do think Typescript could make a better distinction about types that come in from code it has compiled itself (directly seen) and types that come by way of definition files with no code attached ("hearsay" types). (Again, I can't think of any language today that trusts code versus symbols files so differently, so this would be a new thing.)
Often I want it for the: I'm looking at the JS or its documentation right now and it would let me call it this way, but for some reason the Community types are too strict and I don't want to file a DT PR and get into some philosophical discussion about authorial intent versus JS as written versus documented examples and which is "most true" so I'm just going to have to cast this API to any for now and call it a day.
But I can also see the point in: don't give me strictness errors outside of the fence of code you are compiling for me right now in this project. And maybe more unsoundness tools, such as option to treat all return results as `unknown` and force defensive coding when using outside APIs. In general I think `unknown` isn't used enough in community types (it is still "too new").
Though `unknown` is also maybe too defensive for a lot of commmunity types, too.
Also, if you want to code that defensively, you could always replace community types .d.ts files yourself with ones that use a lot more `unknown`.
That may or may not be precisely true, but there are languages that do things that are in that same ballpark. For example, Kotlin on the JVM "knows" when you're calling Java code and it handles certain things differently (null) than if you were calling Kotlin code- even if the code is from pre-compiled libraries.
And considering that I already have a tsconfig file that describes my project and applies rules to only the code in my project (IIRC, there's a toggle to control whether the TS compiler analyzes/compiles your node_modules), I don't see why it would be such a leap to just have an event-stricter --strict flag that didn't allow known-unsound code in my project's files.
> But I can also see the point in: don't give me strictness errors outside of the fence of code you are compiling for me right now in this project. And maybe more unsoundness tools, such as option to treat all return results as `unknown` and force defensive coding when using outside APIs. In general I think `unknown` isn't used enough in community types (it is still "too new"). > > Though `unknown` is also maybe too defensive for a lot of commmunity types, too. > > Also, if you want to code that defensively, you could always replace community types .d.ts files yourself with ones that use a lot more `unknown`.
That's all a little intense, IMO. There's a clear difference between trusting a third party library's API/types and having the compiler help you catch bugs in your own code. If I call a third party function in my code and the documented types all check out. Then, if I experience a runtime type error, that's a bug in the library, not a bug in my code. This can happen in any language with escape hatches like type-casting and it's not appropriate, IMO, to guard against that. Put another way: if that is something that is a concern, then you shouldn't be using a third-party library.
Ideally, one should compile TS with `--strict`, otherwise there's little difference with JS. With this in mind, it's quick and easy to switch to TS tooling. Afterwards, one can incrementally adopt stricter typing, culminating in adding `--strict` to your `tsconfig`.
In reality, since `--strict` is false by default, I'm concerned people erroneously assume that their JS code is type-safe after the first step, when it really isn't. In other words, it's no different than JS, except in name only!
Compared to what? JSDoc made it even easier, you didn't even need to strip anything, as the "types" were just comments. This comes with its own problems, who want to program with comments? But it didn't require any changes to use for us who want nothing to do with TS.
The stripping part is just a fallback option if you decide to move away from TS, you never actually use that in practice.
TypeScript supports providing types via JSDoc comments[1]. This gets you use all the IDE language features you'd get using TS, including highlighting type errors. I actually use this all the time, since I have plenty of scripts that are complex enough that I want type checking but not complex enough to warrant a compilation step.
There's also Google's Closure Compiler[2], which uses JSDoc for its JS type annotations.
[1]: https://www.typescriptlang.org/docs/handbook/jsdoc-supported...
Compared to a new language...
This actually touches on one of ReScript's supposed unique selling points amongst the functional compile-to-JS languages. Namely that the JS its compiler generates is so clean and readable that, if you end up deciding you don't want to bother with ReScript any more, you can just take the output from the final time you ran the compiler and treat that as a plain JS codebase to continue working on. Exactly how true that is, I don't know.
If you're "all in" on TypeScript, you'll love Rescript. It's sooo much faster. Been using it for 3 years now.
Providing type declarations for every third party lib you might want to use, especially in an ecosystem like Javascript's which relies heavily on them, gets tiring pretty fast.
Typescript manages to get past that because it has reached a level of adoption now that most popular libraries will have a @types/<lib> package also but it took a long while to reach that stage.
Curious if anyone has used ReScript at a larger scale (and does not have the resources of, say, Facebook) and what's their experience been like.
Former coworkers have messaged me saying that they miss writing ReScript and wish they could convince their team.
We have about 1200 ReScript files on both front-end/back-end. It's great. It feels much safer to refactor and write new code.
We use TypeScript in some places, like TypeORM and we're able to consume those types on the Rescript side. Rescript generates and consumes typescript types via gentype.
I'd strongly recommend you try it!
If you need to add types to a JS library that still doesn’t have them for some reason, you’re actually doing less work than if you didn’t add them.
Add the types as needed and you’re good.
[0] https://www.typescriptlang.org/docs/handbook/2/template-lite...
"ReScript has no async/await support."
"ReScript has no special debugging support or source maps."
Sorry but aren't these issues fairly glaring problems? They're hand-waived away because the project is small, but I feel like they'd become quite major eventually?
The second one does sound like a fairly major thing though. The promise syntax shown in the article to get around the issue looks like a massive code smell.
(to be clear, this is sarcasm, please don't do this!)
/index.res
/posts/index.res
You’d need:
/index.res
/posts/posts_index.res
Pretty annoying
* the use of decorators in even the most basic example
* no async/await. You fall back to Promise.{then,resolve}. The example given is not that clear to me.
* You can't have two files with the same name in different folders??
And in general, for me, the ability to be a little less strict at times makes Typescript way more easier to deal with. It's a 80/20 thing. Most of the time I want type enforced but in some situation, I know it's OK and I just want to move on with my day.
Using fp-ts there is never a need for async/await and the code is still linear, (Promise is transformed to TaskEither<Error, Result>, similar to the example in the article, although you can ignore the error and just map over the result, handling the error somewhere near the end of the chain).
Problem with async/await is that the syntax is so easy that eventually the whole codebase gets polluted by it, even parts that could have been completely separated.
From the coding perspective, the problem with promises arise when there is a need to bind the intermediate results. You can either store them in an object and return that object for the next .then(fn) call, or you can nest inside a promise. I guess nesting is what annoys people the most (pyramid).
Curious, why is this bad?
When code is sloppily written you realize that at some point you can't use much of the existing code outside of async.
One nice example of polluting the codebase is having async local storage. Now everything that reads from the storage needs to be annotated async and now your initialization pipeline might be insanely async. Good way to avoid it is to read the whole local storage at the beginning (having a sync interface) and then everyone just reads without await.
From recent experience, I did exactly that with storage and ended up removing thousands of async annotations that were no longer necessary.
Similar "mistakes" happen for other things and then at some point you are putting loading guards everywhere because your async operations are always awaiting and letting the UI update when it should not.
Can we agree that JSX is not a valid JS? So decorators are required indeed to simulate "JSX magic"
> no async/await.
As I mentioned, it's not an really an issue (although I though it will be). At least from my experience.
> You can't have two files with the same name in different folders??
This sucks indeed :)
The problem that those 20% corrupt the value of another 80% :/
Neither is rescript - so why not make jsx a first class citizen?
Doesn't this mean we're basically back to callback hell? This was one of the primary criticisms of Node before async/await was introduced.
Await/Async kind of streamlined all this.
Ah yes. The magic word "just". You "just" do something that does something.
And yet even the example in the article uses Promise.then and eventual callback hell.
ReScript requires a lot of commitment, as you have to completely rewrite each module to 100% comply with the type algorithm.
Typescript even transpiles when it encounters type errors.
We started using Rescript by adopting individual files until most of our codebase is ReScript. We still have Typescript lingering around but folks _choose_ to refactor it to Rescript because they've found it easier to work with.
Rescript doesn't make you do strange things. The async/await stuff is annoying for sure, but after 3 years of using it, we've kinda forgotten about it.
I got hit by this literally yesterday. It took me a while to understand this mess.
A more thorough explanation of the whole kerfuffle : https://ersin-akinci.medium.com/confused-about-rescript-resc...
If you think of javascript as a compilation target rather than a language, typescript is just one of many languages that can target that. And I'd argue that even javascript these days is transpiled to what runs in the browser. It might be the same javascript dialect. But minified/obfuscated etc. But more commonly, it's more than just that. In short, modern javascript development involves transpilation/compilation. It just does. The whole scripted/interpreted vs. compiled distinction that people used to make is less relevant these days. It pretty much always involves some kind of compiler.
And if you are going to use a compiler, you might as well use a proper one that does some useful stuff like prevent bugs, check types, optimize, etc. Typesystems have come a long way in the last 20 years. In short, there is no technical reason to be using Javascript exclusively in 2022. Whether it's Clojure, Elm, Kotlin, or other languages; they each have in common that they have js transpilers that work quite nicely and type systems that are definitely a level up from the unholy mess that is Javascript's "it could be a string or some object or undefined, but who the hell knows". Some people actually prefer that. Other people want no part of that kind of sloppy typing. And the good news is that there is no technical need to have any of that.
I've been using Kotlin-js for the last year for a web application. The tool chain has some rough edges but the language is a joy to work with generally also for browser development. Definitely an upgrade over typescript, which I've also used in the past. And we have quite a bit of multi platform kotlin code that we also use server side. A lot of what we do is increasingly multiplatform and not explicitly dependent on the JVM. We could choose to use that code also on Android or IOS (via the native compiler). With compose web and other emerging Kotin web frameworks and the upcoming WASM compiler for Kotlin, I suspect it's going to become a lot more popular to use for web applications. With WASM, transpiling to Javascript will ultimately become a thing of the past. If you are compiling, you might as well produce WASM. Short term there are some open interoperability issues with browser APIs of course. However, nothing that can't be solved long term.
For what it is worth, we are using the Fritz2 framework, which is quite nice. That was definitely a bit of a bet a year ago but we've stuck with it and they are getting close to a 1.0 now. We might switch to compose web at some point but it looks a bit early for that right now. One plus point with Fritz2 is that it comes with a nice component library, support for themes, etc. So you can get up and running pretty quickly without spending a lot of time on custom component design.
- Elm: not general-purpose enough (only useful for UIs), plus has a tendency of making drastic changes between versions (remember how loudly people complained here? [0])
- Purescript: the designer of the language, Phil Freeman, has stepped away from this project, and it doesn't seem to have gained sufficient traction
- Rescript: I'm put off by its ocamlness; and worry whether it will repeat the trajectory of Flow, which has essentially become irrelevant
Not really, it just has a slow release schedule. Over time it is relatively stable.
Not a single thing has changed about it the last two years and the creator has communicated that it will probably stay mostly the same for quite a while.
Yes, there have been some bigger changes in the past but that is fair game for software that hasn't hit version 1 yet and it was communicated that it might happen.
The drama is mostly an issue caused by misaligned expectations: Many people assume that open source projects should be developed openly with everyone being able to contribute and having a say about the direction. Evan, the author of Elm, prefers to keep tight control of everything. The approach has some advantages and disadvantages and I can see why people might decide to stay away from the community but honestly if you just want to get work done in Elm, it is not much of an issue either way.
Elm is probably the most stable and reliable choice for frontend code and helps avoiding the churn that happens in the JS ecosystems.
Business logic can be shared with .NET and it has lots of ways to interoperate with JS. There's even a TypeScript converter though of course it's not as pleasant as "yarn add" and YMMV : https://fable.io/ts2fable/
Here's a demo of building some React components in F#: https://www.youtube.com/watch?v=a6Ct3CM_lj4&t=860s
Does ReScript solve that? If so, how? In my experience this is mostly an issue with data/functions coming from outside sources (Return values from HTTP calls to endpoints you don't control being a big culprit). Sure, you can write type definitions for that but that doesn't mean anything unless everything is manually validated/checked at runtime as nothing really guarantees that the type definitions are actually correct. Does ReScript handle that automatically?
An unsound type system means that you can write code that compiles, but experiences a runtime error caused specifically by the types (not the values or the business logic conditions) not actually being compatible. The famous example is having an array of a subtype being used as an array of the supertype:
function doStuff(animals: Animal[]) { animals.clear() animals.push(new Cat()) }
const dogs: Dog[] = [new Dog()]
doStuff(dogs)
dogs[0].bark() // <-- type error
In a sound type system, that code would not compile because we know that you can't treat an array of Dog as an array of Animal in general.
I believe that code does compile by default.
If you turn on the strict flag, that exact code wouldn't compile. BUT, if you wrote a class method instead of a top-level function in the above snippet, it STILL would compile.
> The "issue" with TS is that everything type related completely disappears after the build step and that needs to be kept in mind in development. Some developers struggle with that, especially at the boundaries to external APIs/libs/whatever.
I agree that a lot of devs struggle with that, but that's not really relevant to the type system being sound, and has nothing to do with the example I wrote. It can be proven to be incorrect at compile-time, so the compiler should reject it.
In fact, most of the "hardcore" statically typed languages you hear about have full type-erasure: Haskell, Rust, ML, etc. Yet, they have reputations for very strong and strict static type systems. None of those languages would let the above garbage compile.
I bet there are runtime checkers that use some kind of reflection, that would be the next best thing. But I also bet that those force you to annotate/decorate everything.
const user: User = JSON.parse(…);That's where Typescript clearly has the advantage; being just JS with types makes it much easier to get started, and the fact that its #huge also helps a lot.
It's a bit sad as I think ReScript is much better on many fronts: the type system with crazy good inference and soundness, very easy to configure and add to existing projects (it just outputs JS files even with TS types), the module system is amazing (gone with imports) and creating simple bindings to existing JS/TS is also quite easy once you understand the basics, I'd go as far as saying it's easier than TS . It's also really fast, both the compilation as well as the JS it outputs.
Because of the adoption hurtle I doubt it will be as big as TS, but I really hope it gains enough momentum and usage to just sit comfy in its niche, for that I think it needs to grow a bit further.
I do think the ReScript team has made incredible progress on all fronts; I think ReScript is much easier to pick up than Reason, because of the language tweaks, but also the new website is so much better than the scattered docs in multiple places.
I hope it will continue to improve and more people will give it a go!
A couple of years ago I looked into Reason and really liked it, but the toolchain wasn't going anywhere and it didn't see a lot of adaption back then.
ReasonML can compile to native, rescript can’t. Reason still exists as a separate project, and projects that have been rewritten into reason will not necessarily switch.
ReScript lives on though.
Then the messaging on the name change was unclear, and the fact that Reason still exists (walking dead, but the name is still out there) made it all very unclear to everyone what was happening, and I think that caused a massive amount of damage to the momentum.
But then again, it's a great language that's moving quickly, so I expect it will continue to grow. Certainly my company is built on it.
There are useful comments in my (shameless plug) post about my same transition:
Btw, for Material UI there are already bindings [1]
I mean TS has that problem too anyway. They're terrible.
By this measure ReScript is still a niche language.
After all if a joke script has more followers then it's better to tone down the marketing material.
No. No it's not. It's the compiler's fault.
Though proper error reporting is quite hard and too many tools transfer the burden of figuring what happened to the user.
Most languages "aid the user" with better error locality by requiring the user aid them with far more type annotations. Lack of error locality is presently a downside of relying on pervasive type inference (at least in both OCaml and Haskell).
I expect there's room (and responsibility) to improve, and so I do accord the language some of the blame. But error locality can be recovered by adding back some of the annotations that another language might require, and it can be optionally deferred until the locality is desired. I don't think it's right to say that that's requiring more help from the user than the baseline, and I think it's right to place some of the blame on the user misusing the tools if they're not adding enough annotations to get the kind of error locality they want from the tool they're using (as noted in the article, the author stopped doing that, although it may've been an overreaction).