198 points · by bubblehack3r · 4y ago · 198 comments
I was reluctant to introduce a build step (having got used to the simple refresh cycle of a browser plus vanilla javascript) but I am pleased to say that this is a bit of a non-issue now with modern tooling like esbuild et al.
I still avoid NPM like the absolute plague, but the good news is that tooling like Deno have made typescript first server-side development in the ECMAScript world a total joy.
I've said it before - it's like floating through the air. So serene, so expressive. A true joy.
"Decent type systems" are usually in your way (especially if you want to quickly prototype something), and despite "decency" have abysmal tools (like "hey I've changed this function signature, update all call sites etc.)
[1] It's getting more and more complex, but even if you write something like this, it's still aiming to help you:
Partial<Record<typeof keyof SomeEnum, boolean>>>Some issues with TS are:
- There is no hard guarantee at runtime as everything is partially/optionally typed (including your deps).
- The types are not used to produce faster code at runtime (like in a compiled language).
It is almost like TS leaves half of the benefits of type checking on the table, obviously by design by being a JS superset.
You can get very close if you place fine-grained, well tested, type guards at IO boundaries, wrap poorly typed or overly dynamic dependencies, and have good discipline about internal boundaries. It’s a lot of work up front in a greenfield project, but it really pays off.
> The types are not used to produce faster code at runtime
Not directly, but in my experience good up front interface design tends to produce either immediately optimal JS (eg it tends to be monomorphic) or makes optimization much easier (as it makes any refactoring easier).
Edit:
> I like type systems as you can design with types and check things tie together before even running the code. This gives you very fast iteration cycles compared to CMD-R refreshing the browser/code.
I’d be remiss not to emphasize this! And not just skipping the reload cycle, it lets you skip a whole lot of test runs too. Type error in editor? Yep, those tests are gonna fail too.
Most typed languages don't have hard guarantees at runtime. With java, using reflection you can do all kinds of weird things at runtime. C++ has fewer guarantees because there is no VM and can't even introspect objects to see their real type. Dependencies are a real issue with TS, but many libraries are written in typescript and the type files are really robust.
>> The types are not used to produce faster code at runtime (like in a compiled language).
The V8 intepreter will actually do this at runtime. Usually it takes less than a second for v8 to optimize the javascript, and it will recognize that many functions and objects use the same interface and optimize appropriately. If you think about it the types only help so much because once you have the code graph, it becomes really easy to find the type and optimize the memory layout.
TypeScript also allows me to refactor fearlessly, which substantially improves the quality of my code as I can do mini-rewrites without worrying about breaking interfaces.
I see this sentiment a lot but I honestly can't think of any non-trivial bugs that TS has caught for me. 99% of the bugs it catches I would see 1 second later when my page hot reloads and crashes.
Even before Deno made it easy, it was straightforward enough to configure a simple tsconfig and just run tsc. Much like cargo, there is a lot to be said for "it just works" tooling - especially for beginners or even new programmers.
It is probably fair to say it is one of the most influential and impactful languages of all time. There's even the future possibility of much of its type syntax being absorbed back into JavaScript: https://github.com/tc39/proposal-type-annotations
TypeScript brands itself a "superset" of JavaScript. In practice, it arbitrarily invalidates completely sensible JavaScript idioms.
[1] https://rescript-lang.org/docs/manual/latest/pattern-matchin...
Such as?
I was not pleased when it told me I have have to do
this.blahBlah = value
in the constructor because it didn't quite catch, and maybe still doesn't, that
Object.defineProperties(this, { bla: { value: ... } blah: {get, set} })
is completely legit
That said, I do prefer ts to vanilla. It's less work than maintaining d.ts files
Also, try implementing a function that takes keyword arguments, some of which are required, and some of which have default values.
I'll wait. When you're back I might've remembered some more.
... as comments. Which superficially resemble the syntax of type hints but do nothing. Which has to be one of the worst language design decisions of all time.
By no means is it perfect, the language doesn't enforce the type rules, but that the developer has the option is far better than not. As far as I can tell the proposal would pretty similar to Python; one can misleadingly or accidentally misuse type hints like the following:
def myfn(a: int) -> str:
return int(a)
print(myfn("42"))
But when done right, it gives you a leg up when you come back to read your own code or scan over someone else's. When you're reading over other's code in group programming assignments, comments make a world of difference (a niche example).It is a choice, but its use in code might just inspire someone to investigate further - my own introduction to types in programming came when I wondered what these oddly placed colons and arrows were in some Python I came across. If they do add these annotations to JavaScript, some future programmer browsing the source of a web page may well just stumble upon types and have a whole new world of theory opened up to them - I'm all for it.
There's also no way to share and reuse types in comments. Do you copy paste comments to "type" things? What about complex objects? What happens if the comments get out of sync? How do you test them?
I used to be a typescript skeptic too, but much of that skepticism tends to come from drastically underestimating the power of the TS type system.
Typescript has been doing a fantastic job, and this proposal is continuing in that same vein, truly absorbing as much of that as possible back into JS!
Kudos to everyone involved, great effort!
And re "[the type hints] do nothing": The section at the end of the proposal clearly explains why that must necessarily be the case: Evolutions of JS must not break the web (especially) for the users.
Quoting: "TypeScript's model -- which has been highly successful for JS developers -- is around non-local, best-effort checks. (...) Additionally, defining a type system to run directly in the browser means that improved type analyses would become breaking changes for the users of JavaScript applications, rather than for developers. This would violate goals around web compatibility (i.e. "don't break the web"), so type system innovation would become near-impossible. Allowing other type systems to analyze code separately provides developers with choice, innovation, and freedom for developers to opt-out of checking at any time."
So this proposal provides the best possible path forward for JS, based on what folks are voting for with their feet by using TS: Making JS compatible with TS-style type hints that can be used by external tools (i.e. not the JS engines executing the code at runtime) to validate the code in a best-effort manner while the developer is looking at it, while not changing JS runtime semantics and thus never breaking the code while the user is running it.
I'm not the biggest fan of static type checking (especially in a language like Javascript, where it isn't used for safety guarantees), but it has its uses.
The "as comments" part of it isn't about syntax. They really mean no runtime overhead/behavior. (I don't think they should have put it that way -- it's just going to cause confusion.)
Is there really any question that "no runtime overhead" needs to be an option? (I think any proposal that didn't include this would be DOA.)
It also seems clear to me it needs to be the default option, for multiple reasons (language changes should be backwards compatible as much as possible, it should be easy to adopt new language features incrementally, type usage is an application-level concern.
Note: there's nothing in this proposal that prevents run-time enforcement. Good design limits scope but keeps your options open.
I know a lot of people like it but it just seems like an ugly hack to me, extra syntax for the sake of an abritrary third party tool. I know I'm a dinosaur. I want to go back to the days of JQuery modules and FTP. Feh.
My main gripe with projects becoming verbose is that the code becomes hard to understand at a glance. Functions that usually could be 10 lines are now 15 lines becomes of the formatter and each line looks more gibberish because everything has a type. You have to manually filter out that noise. The best way I can describe it is that entropy is increased in order to get type safety.
Most plain JS projects use some build tooling even without compiling TS, my work projects are no exception. When I started the job, the build tools (Rollup and Terser) worked just fine and had been in place for years. A short while later I made the case to switch to ESBuild to improve iteration speed, which took a couple hours maybe? It’s been almost totally untouched since. And if I had more time, I’d be able to gradually convert the code to TS without any additional tooling effort.
I get that tooling pain in the JS/TS ecosystem is basically a running joke at this point, but no one is forcing you or anyone else to update anything. Plain old tsc still works if you want to keep it simple (and it’s what I recommend to anyone who wants to try out TS and feels confused or intimidated by the whole Tooling Thing).
To each their own of course, but living on both sides of the fence… the JSDoc-types side isn’t nearly so green as it can sometimes sound.
Here’s hoping the types-as-comments proposal keeps gaining traction. I’ll still use a build tool to strip types out for prod, but I think the no-tooling/JSDoc-types crowd would benefit a lot from a syntax much closer to TypeScript too.
But TS is very viral by nature. You can only go in one direction (JS -> TS). TS promises "type safety", which is mostly a lie, but sounds really good. It also promises to be purely additive, so choosing it seems like a no-brainer. TS is a next step in a JS-engineer career, once you learn it it's hard to admit that it was a waste of time. Especially when there's nothing but praise around, humans are conformist by nature.
Being viral doesn't make it good. But it means that it will keep spreading, until community gets a TypeScript fatigue.
The typings on the class variables are useful to have. There are also typings on the function signatures, not a huge deal.
In the method bodies there are almost no typings as all of it is already inferred. Seems pretty readable to me.
export interface IDomEvent {
<K extends keyof HTMLElementEventMap>(element: EventHandler, type: K, useCapture?: boolean): BaseEvent<HTMLElementEventMap[K]>;
(element: EventHandler, type: string, useCapture?: boolean): BaseEvent<unknown>;
}Looking at the code there is an awful lot of 'null's returned which I find hard to work with but that is a different topic.
Sadly, the majority of people writing Typescript rarely care about descriptive and readable code these days. Somehow the focus shifted from using types to better understand complex systems through the code itself, to writing whatever polymorphic union type abomination that yields the best IntelliSense auto-completion in VSCode.
In particular there is no built-in ADT syntax, but the type system does support ADTs using the aforementioned polymorphic union abominations, so it is possible yet tedious to write them.
They are in a tricky situation because TC39 really does not care about TypeScript at all when introducing new features into JS. So TypeScript is doing its best to avoid breaking future compatibility with a standard they have no control over. Sometimes this makes the language worse, but they are playing the long game.
I have no doubt codebases with polymorphic union type abominations exist, but I wouldn't say they are the majority, far from it in my experience.
It also seems to me those are a case of "problem lies between chair and keyboard", not a fault of the language. Bad code can be written in any language.
Agreed. And in fact, the founders of a project having explicitly chosen TypeScript is often in and of itself an indicator that the team cares about code quality and writing style.
As you say, you can write poorly in any language. But people who care about quality choose TypeScript.
TypeScript is great, but it is also still very far from being complete in my opinion.
I used to do mostly Java and a bit of TypeScript, changed teams and now do mostly TypeScript and a bit of Java, and this unfinished feeling is striking, even for relatively basic things (enums).
I think the modern compiler options / TypeScript rules such as "hey this variable can be undefined but you didn't specify it", "hey, it can also be null, don't forget that" are commandable, but just don't work well for the web. I know it's configurable, but it just makes for a bad experience.
Still, love TypeScript. I wouldn't do any JavaScript project anymore, installing the TS compiler is always my first step.
I'll never understand why people need a programming language inside a programming language and refuse simplicity (i.e. using jsdocs, which has perfect IntelliSense support).
However I tend to only use /** a comment */ before a type definition or argument which will add the comment along with the type in autocomplete.
I get the feeling you've stumbled more on the debate about commenting code/inline docs vs code that self documents. My general impression of Javascript developers is that they are comfortable adding comments whereas Typescript people are not so comfortable for some reason. Maybe because a lot of them are coming from Java and C# where writing clean code™ is more preferable to adding comments.
Personally I think there's a middle ground. I've met some Javascript developers insisting on adding a comment before each statement and I've met some java developers having a no comment policy in their codebase (so that pull requests wont merge if there are comments).
If you want to have documented codebases, work with people who document their code. You’ll find that typescript doesn’t always mean undocumented, and incidentally you’ll find that documented doesn’t mean high quality.
Most high quality codebases in the JS ecosystem after 2016 ish are in typescript.
It is so liberating to type a variable as `any` when sketching new code, figuring things out, that I would venture to say that any language not having the `any` type actually actively hates the developer.
[1] https://www.typescriptlang.org/docs/handbook/2/everyday-type...
i.e. "it stays out of your way if you don't actually try to use it"
Actually I thought of using C# a few months ago, and I was like "Oh wait, does it even work on other platforms than Windows now?". Sure I'm not a C# developer, so I'm not up to date on C# news, but that's an issue if your goal is to drive adoption. Everyone that has heard of C# should know that it's now cross-platform.
I think Godot also supports it
"go to definition" -> goes to type definition
Microsoft makes it intentionally impossible to get anything done in their ecosystem without having "great tooling".
Java does it too?
But yeah, the tooling is kind of bad and it is all written in OCaml, while TypeScript is in TypeScript…
Native bundlers like esbuild, swc etc. are mainstream now but they came much later.
Just like MS eventually did with C# too. After the C#-compiler was reimplemented in C# (Roslyn), that’s when the language was truly allowed to develop. And it also made it much easier to make C# a truly cross-platform language.
When the language-designers don’t have to use their own language, they have objectively much less motivation to improve upon the language or it’s tooling than if they do.
The Flow-team didn’t use Flow to write Flow and that shows in its lack of development, its lack of tooling, its lack of contributors and ultimately in its lack of adoption.
I don’t know. I tried to understand the OCaml code and contribute to Flow, and in the end I nope-d my way out of there.
TypeScript is for any kind of project, it just makes your code safer, easier to debug, easier to read / come back to in the future, etc.
> Fast!
That doesn't mean anything.
Especially for a small project, the TypeScript to JavaScript compilation will take milliseconds, there is no speed impact at all.
The main speed impact is in developer productivity though. If something ain't working right, now I first gotta fix the types before I can see if I've fixed the actual logic.
I imagine if my codebase was more "OOP-y" (i.e. if I replaced every layer of my domain model with 3 layers of dependency injection, turning the whole thing into an inscrutable ball of spaghetti like the cartel wants me to) I could probably iterate without breaking the types.
But for any sane developer having made the mistake to touch TypeScript, the capability to strip the types and run the code with broken types, is essential.
"But then why have types at all?" Exactly. They're a crutch for people who want their IDE to understand the code instead of them.
Is one side or the other right or better? I dunno, I'm not qualified to answer.
A perfect scenario for me is having all errors in the project caught by vscode. At the moment vscode only checks files that are currently open. I think type checking should only be done when building to some sort of production or realtime in your editor. Templates like "create react app" can report runtime errors but it's somewhat strange that it also report typescript errors. (although understandable given that it wants to be tooling agnostic)
One potential major upside with adding optional type hints to javascript is the ability to run typescript files directly in the browser without needing to strip types in a build step. Advanced type checking could be done the same way we use linters like eslint.
You’re free to hold that opinion, but I think you see (based on downvoting) that your definition of a “sane” developer is not as universal as you may have thought.
Personally I almost never see any value in running known broken code.
If I need to run/test a subset of my code without a complete working system, I have unit-tests for that purpose.
Personally, I’m marginally on the side of using TS even for small 1-2 person projects, but only slightly, and I can understand the case not to.
Well designed projects are no more complex than they need to be, and for many smaller projects that means — at least for web ones — that you have few significant “type barriers” where types are non-trivial and communicate or structure things in a way that is useful. And the type-heavy areas also tend to be where the app is ingesting data from a non-local source — exactly where static type checking is useless. (It’s always extra annoying when you’re fighting the type checker when writing the code that really ensures the data has a valid form.)
And recompile on every change, gotcha. I am emphatically not doing either.
EDIT: for future reference, `"type": "module"` is not part of the fix but the thing that opens that particular can of worms. Rotten ones.
When it came out alongside Dart, I thought Dart to be the better, cleaner solution. After all, Google created V8.
Microsoft and Hejlsberg didn't seem well suited to tackle something so lightweight as JS. The whole .net suite seemed like an overengineeres mess to me and MS wasn't liked after the IE6 incident.
But on recent years I came to like TypeScript. It really is just JS.
I was a bit younger and bolder then; I lamented with the lead developer about how vanilla JS was probably not a good idea for what was to be a large enterprise platform. The response I got back was probably what you would expect from a senior developer receiving criticism from a rather newly minted developer: Oh i've tried Typescript, but it's just SO VERBOSE. I feel like I can't get ANYTHING done, etc. etc. etc.
I've personally been all in on TS from close to day one - around 2013 when I started some very early web development (hooray for the AngularJS/Angular days! /s). It somewhat scratches my ego and has been rather interesting to see the developer mindset change, particularly that of vanilla JS developers of old. Response like ones I had have gone from often negative, complaining about verbosity and I guess frustration with anything different from what they are used to, to overwhelmingly positive. Old guards join us, or fade away, I suppose.
sed s/vanilla/pure/g
(my wish for what we call javascript itself)Is there an editor that doesn't work with Typescript? Even without type error integration into the editor view, you could still run tsc in your shell of choice to manually check if everything is OK.
That's why you don't have any issues. The error popups aren't the problem. It's the autocomplete and type popups.
The last few years TS has raised an army of shit devs that code in such a way that it's literally impossible to read the code without your IDE popping up multiple boxes to tell you what is happening. They just search every function name, giving zero thought to where anything lives in the directory structure. They type everything like fucking idiots, with layers upon layers of types across 10+ files, all of which you have to open just to find out you're working with an object that has a couple of strings and a number on it. Of course VSCode will just tell you this when you hover over the variable, if you're using it.
Just wait until you get a project where these muppets have a majority and you'll feel the pain.
There are two main resources I would recommend:
- for those who prefer written content, the TypeScript Handbook [1]
- for those who prefer video content, the first couple videos of Jack Herrington's No BS TS series [2]
Other than that, just start using it. My main advice would be that your TS code should look as much like JS code as possible, ie don't explicitly type everything, just rely on inference where possible. Basic generics can be useful occasionally, but most of the "Type Challenge" type stuff is only really useful to library developers.
[1] https://www.typescriptlang.org/docs/handbook/intro.html
[2] https://www.youtube.com/watch?v=LKVHFHJsiO0&list=PLNqp92_EXZ...
And then even if you don't I'd still say reading the docs and just browsing existing code assuming you already know JS would get you all the way there.
Not sure if it's <250 pages though.
You mention "within the last 5 years" without also taking into account the absolute explosion in the popularity of becoming a software dev in the last 10 years. So of course theres going to be a lot of bad (and some good) devs. With TS being one of the literal most popular languages in use right now, of course a lot of bad code will be concentrated there, but I wouldn't blame TS itself for it.
You can also blame hiring practices somewhat for it, since a lot of places I've worked for even myself recently hire anybody who can recite a couple ECMA features rather than focusing on good dev practices in general.
It is amazing that the whole langserver stacking that volar does is possible at all - I don't believe there is any equivalent prior art that worked as well as it does. Despite all the complexity the end user experience is pretty good. If someone had mentioned to me this kind of cross language type-checking can work as nicely before I used volar I would have been super skeptical.
Sure it has its caveats. But it is also completely possible to use vue in pure typescript.
I don't fault them for having native jsx support, React was just too popular in the target user base. I do hope that someday js+ts gets kotlin style builders, but until I'll gladly use volar.