top | item 11296491

JavaScript libraries should be written in TypeScript

386 points| ingve | 10 years ago |staltz.com | reply

275 comments

order
[+] STRML|10 years ago|reply
I completely agree with the sentiment that typed libraries are more stable and self-documenting. You can autogenerate documentation from typescript and it's guaranteed to be up to date, unlike JSDoc comments.

I personally have converted a few of my libraries [1] [2] over to Flow. It helps me personally, catches a lot of bugs, and does a great job of self-documenting while not getting in the way.

Flow has a lot of bugs and a lot of growth ahead of it, but it is far easier to get started with than TS. I highly recommend it.

1. https://github.com/STRML/react-grid-layout/blob/master/lib/u...

2. https://github.com/mzabriskie/react-draggable/blob/master/li...

[+] Eridrus|10 years ago|reply
> Flow has a lot of bugs and a lot of growth ahead of it, but it is far easier to get started with than TS.

I know this was definitely the case when I started using TS a few years ago, but they recently added support for compiling .js files in your typescript projects, so you only need to deal with the compiler one file at a time.

Admittedly I haven't used it, but I think it should have made the migration easier. Probably still not as easy as Flow, but easier...

[+] mstade|10 years ago|reply
Starts off with:

> Typed vs dynamic is a rather controversial topic, so I’m not trying to spark that discussion all over again.

Goes on to explain that typed is betterer...

The article doesn't really offer up any real arguments as to why you should specifically use TypeScript, but really just says typed is nice and everyone lints anyway (not true) so the step up to a type system really isn't that big of a deal (also not true.)

Not really sure what point the author is trying to make.

[+] nateabele|10 years ago|reply
Context matters. Some people, while writing their own application code, find types to be annoying, a nuisance, or whatever. That's a personal (or team) decision.

This article is targeted at authors and maintainers of high-adoption libraries. It says so right in the second paragraph.

And, frankly (speaking as someone with experience on this topic), he's right. Maybe static isn't always the answer, but in the context of high-adoption libraries, a little bit of effort to improve clarity and strictness is a huge lever for cutting down on wasted time of thousands of developers everywhere.

> The article doesn't really offer up any real arguments as to why you should specifically use TypeScript

Did you read it? He offers the Git/Mercurial comparison of TypeScript's growing popularity.

[+] diem_perdidi|10 years ago|reply
I may choose not to document my code or not to test it - because it's just a one-time script, because it's going to be thrown away soon, because all my coworkers know what the code does... It's more than debatable of course, but it happens a lot in practice. However, if I write a piece of code that will be re-used a lot (inside my company, by friends...), I will do more of that (tests, documentation). I expect the same from libraries authors, whose explicit goal is to be re-used by others. The author's point is that typings is similar to tests and documentation - if you want people to use your projects, typings will help them (it actually serves as a good start for tests - catching bugs that cause compilers errors / warnings - and documentation - what your functions accepts is a very good start), and it adds eg. autocompletion / 'go to definition'. As a user, feel free to use Typescript or not. As a library author, help your users by using types.
[+] pka|10 years ago|reply
The point the author is trying to make is that all Javascript libraries should be annotated with types. Not necessarily Typescript, but that's the popular choice right now.
[+] a-saleh|10 years ago|reply
I think the core of the argument is this:

> some type definitions are better than none. It may be quite feasible to build conversions from .d.ts to FlowType type definitions or other languages type definitions, so whatever the Future of Typed JavaScript will be, having .d.ts files today will help us in the future to migrate towards it.

So I read the argument as "Give me at least slightly automatically verifiable api with your library".

[+] jowiar|10 years ago|reply
I think this is a bit of a hasty claim with a bit of truth to it, sort of like if someone said "All JavaScript libraries should be authored in CoffeeScript" in 2010. A cambrian explosion occurred, then the community eventually coalesced. Coffeescript itself isn't (and wasn't) perfect, but it pioneered an approach that led to a whole lot of progress in JS.

A better framing of this is: "Type systems are good. The JS community should sort this out in the next couple of years and will probably a standard approach, but it's worth diving into the assorted tools that exist -- TypeScript, Flow, and any others -- to understand the ecosystem and find pain points."

[+] betageek|10 years ago|reply
Unfortunately a few of the more visible members of the JS community seem intent on writing blog posts like this, I'm super tired of 'I have seen the light, this is the 1 true way, anybody who doesn't do this is an idiot' ragebait. I guess it's a sound content strategy (296 points!) but makes me think a lot less of the people who do it.
[+] bryanlarsen|10 years ago|reply
It's more like: "we have now determined that type systems are good and it's going to be in Javascript at some point. It might be like Typescript, it might be like Flow, or it might be something else but if you use Typescript or Flow now now your transition to the final product will be easier. Plus in the mean time it'll make things a lot nicer for anybody who is using Typescript/Flow and your library, or heck just a lot nicer for anybody reading your documentation."
[+] impostervt|10 years ago|reply
I still run into libraries written in Coffeescript, and hate it when I do, because I don't use it and have a hard time following it.

Javascript libraries should be written in Javascript. Worship the one true God!

[+] lloyd-christmas|10 years ago|reply
Typescript isn't all that differentiable from ES6. While I'm generally on the vanilla train, feeling fairly compelled to use it when messing around with angular2 has made me very much appreciate it. Change your .js filename to .ts and it will still run, which makes the typing just an added bonus.
[+] cpitman|10 years ago|reply
Except this really isn't an issue for TypeScript, it reads that close to JavaScript.
[+] blakeyrat|10 years ago|reply
This is like the fourth or fifth post in this thread where people are confusing CoffeeScript and TypeScript. Why is that? They're totally different.
[+] mattferderer|10 years ago|reply
Simple solution - offer the compiled file in the library. Everyone wins.
[+] slang800|10 years ago|reply
Then just compile the library and everything will read like really well-written JS.
[+] ungzd|10 years ago|reply
And then new transpiler language appears, with "real" type system, not java-grade. And everyone stops using typescript, treating it as outdated technology.
[+] tommyd|10 years ago|reply
You may or not be right, but Typescript seems to be gaining a reasonable amount of attention and traction outside Microsoft, so I suspect its type system may be "good enough" to add a decent degree of type safety while still staying close enough (for better or for worse) to vanilla Javascript that developers, CTOs, etc. aren't put off by the perceived difficulty/risk of a totally new language (also I guess the Microsoft backing counts for something).

There are enhancements to the type system on the roadmap, for example support for non-nullable and variadic types: https://github.com/Microsoft/TypeScript/wiki/Roadmap

Typescript may not be perfect but I'm glad to see it getting more attention as I think it can bring a significant quality improvement to a code base for a fairly small investment of effort.

[+] bodhi|10 years ago|reply
It already appeared, and is called Purescript. It's great, and it's about as likely to gain traction as Haskell.
[+] dceddia|10 years ago|reply
I don't see the point made often, but I think that "Java-grade" is what a lot of developers (the backend ones) actually want. Or, rather, they'd prefer if JavaScript morphed into something closer to Java. I suspect many of the strong supporters of TypeScript come from Java/C# and just want plain JavaScript to be abstracted away.

I've gotta say that one of my main fears with TypeScript is the potential proliferation of code written in heavy OO-style where everything is a Factory or Service or Interface or Impl. And that scares the hell out of me.

I know that TypeScript does not mandate code be written that way. Neither does Java. But TypeScript makes it easier for the Java devs to carry over their heavy-OO habits rather than learning a lighter way of writing code, and that's my worry with it.

[+] maxaf|10 years ago|reply
Are you arguing in favor of everyone sticking to the lowest common denominator technology just because the pace of change is too quick? I would wager that things are changing so much exactly because of this reluctance to adopt new developments at scale. It's a vicious cycle, to be sure, but plain vanilla JavaScript everywhere can't possibly be the savior!
[+] bryanlarsen|10 years ago|reply
One major point of the article is that if such a language appears, the existence of your .d.ts file will make the transition to the new language much easier.
[+] MadcapJake|10 years ago|reply
> not java-grade

If people hate TypeScript like they hate Java, then it's probably going to become the standard.

[+] crusso|10 years ago|reply
At that point, you can always transpile from Typescript to javascript or maybe even from Typescript to the new language.
[+] robert_tweed|10 years ago|reply
I'm not certain I agree. I agree with better type systems, but does anyone remember ECMAScript 4? Which Microsoft vetoed after Macromedia had gone ahead and adopted it as ActionScript 3 (coincidentally around the time they were trying to get everyone to adopt Silverlight). Well that's basically what TypeScript is (with slightly more advanced type support). It's a nonstandard dialect of JavaScript. Something that everyone (especially MicroSoft) ostensibly agreed was not what was wanted or needed.

The alternative to that of course is Babel. Which is standard JavaScript, mostly. Including the draft stuff that isn't ratified yet. But you don't have to use any of that if you don't want. And things like Flow and JSX, which are just plugins so again, you can take them or leave them.

The authors argument eventually distills down to a choice between TypeScript and Flow. He concludes that TS is the best choice because it has the momentum, but that's a false choice. The choice is between Microsoft's TypeScript transpiler and Babel.

If you use Babel you can choose to use Flow, but if you use TypeScript you lose out on everything else Babel has to offer.

And outside of the .Net+Angular world, Babel has all the momentum.

[+] Bahamut|10 years ago|reply
I don't think you understood the point of the article - it was targeted at library maintainers, not all users.

Types often end up a part of the documentation, and internal typing is often needed in libraries to keep track of model state, so having it at the foundational level in the library itself adds tremendous benefit.

[+] _ea1k|10 years ago|reply
I used AS3 at that time and completely hated it. It would have been a terrible approach for JavaScript to adopt going forward. TS is much more suitable for the dynamic nature of JavaScript, IMO. I know that AS3 had dynamic features, but they tended to have a lot of very strange limitations in actual use (it actually felt more limiting than pure Java code in some cases).

I haven't tried Babel, though. It easily could be a better path forward. Does it have some equivalent of the typescript type descriptor files?

[+] maaaats|10 years ago|reply
What does one miss out from Babel, given that TS is a superset of ES6?
[+] mbrock|10 years ago|reply
Or at the very least, library documentation really needs to clearly specify the types of parameters and return values.

I'm positively surprised when I come across a JavaScript API whose documentation actually specifies this very basic information.

Coming from the static typing world, it's astounding...

[+] Maarten88|10 years ago|reply
Yes. And, having worked with typescript, its quite annoying how poor most typings files are that you get from the definitelytyped repository. It's better than nothing, but they are unversioned (so always behind) and often very incomplete.

I agree with the author: types are there anyway, typescript seems to work well enough and has traction now, so please, if you write a library: add those type annotations bottom-up in the library and let typescript generate a nice .d.ts declaration file and standardized module stub around that final javascript library.

[+] mstade|10 years ago|reply
+1

Documentation in the web development world is usually very good with the introduction, getting you excited; but terrible when it comes to reference, the day-to-day type docs.

[+] gexla|10 years ago|reply
Do you have an example which has stood out for you?
[+] rtpg|10 years ago|reply
I've been porting over a reasonably sized project to Typescript for about a year now, well worth it.

Most of the time, the change is just to rename the file to `.ts`. Sometimes you have to change things because (surprise!) there was a bug.

The biggest painpoint is that you usually have to go pick up some type definition files from DefinitelyTyped for third party libs, but it's well worth it. Second biggest painpoint is type signatures (depending on the context, writing out types/definitions can be subtly different... or maybe I'm doing something wrong).

To anyone who's considering moving their JS stuff to Typescript but have hit some issues, please feel free to ask me. I really think it's a plus for sanity when writing JS.

[+] bsr203|10 years ago|reply
I love static typing, but prefer flowtype for js project.

I used Typescript during the initial days while developing Angular 1 apps. Things might have improved now, but transpiling to JS was slow then and had non standard module system. It may make sense to use it for Angular apps as Angular 2 and related projects are written in it. but, for me, it always felt as another language farther away from JS.

Once started using Babel + Webpack, I couldn't think about leaving the flexibility and standard compliance to Typescript (mostly react apps). Also, gave Nuclide and Flowtype a second chance this week, and they dramatically improved. As a drawback, there are tons of open issues on Flow tracker and seems more investment needed.

[+] AgentME|10 years ago|reply
+1 for Flow. I've loved the fact that it's not a build step, so it was really easy to add Flow into my Babel+Browserify projects. I looked at Typescript before, but I didn't want to leave Browserify, and Typescript+Browserify did not look like it was a well-supported path.

Also its strictness about nulls has saved me so many times and has forced me to make better APIs that carefully consider or prohibit them, instead of treating null as a boogeyman that I don't think about until it inevitably bites me.

[+] bitinn|10 years ago|reply
As a js library maintainer and contributor, I do find these arguments flawed:

> There is a culture in the JavaScript community that “types don’t matter”

I don't think that's the case, particularly among seasoned developers: we do care about types and interfaces, but we just don't think writing them down in code is as big a deal as Typescript claims it to be.

> We are already linting because we believe it makes better code.

Linting doesn't require you to write non-javascript, it just works (after configurations). It doesn't force you to write code in any particular ways (see ESLint for example). That's why we find it more acceptable.

> Types are stronger. Types matter.

TS isn't automatically stronger, since TS is a superset of JS, developers can still omit the types. So you either write in proper TS-style and get its benefits, or don't.

And referring to earlier points:

> The types are there. Instead of leaving them implicit, you can just make them explicit.

IMO: there are many ways to setup this contract. And I question the % of type-related issues within a library when you have 100% test coverage and proper linting already.

> Often in JS libraries, the types are vaguely defined as an afterthought when writing docs.

TS can't force you to write strong types, just as JS can't force you to write good doc. You need a stronger will, not a better nag.

My case for writing your next popular library in vanilla JS: your users will already know how to contribute. And you get to choose how to enforce good variable types.

For TS vs JS details, see http://stackoverflow.com/questions/12694530/what-is-typescri...

Disclaimer: my libraries are nowhere as popular as angularjs or immutablejs, but I do intend to maintain them to a degree that may serve thousands of developers.

(Plus the author uses one of my library so I guess they are not that bad)

[+] BuckRogers|10 years ago|reply
This makes sense. For the same reasons you'd want your display driver written in a statically typed language like Rust. I think a good case can be made that Python(3) libraries should be using type annotations as well. Some net gains on software reliability that you may not want or need in your webapp, but is welcome in underlying libs.

While type errors are a small part of problems in software reliability, we should take everything we can get. At least in things thousands of millions of users are going to rely on.

[+] onli|10 years ago|reply
The title is needlessly inflammatory (hope that's the right word). It's the original one, but the article states clearly that it is an advice for libraries that are intended to be used by thousands of developers. Maybe the title could be changed to "All big JavaScript libraries…"?
[+] alimbada|10 years ago|reply
What's a "big" JavaScript library? How do you know how widely adopted your JavaScript library will be?
[+] zimmerx|10 years ago|reply
This does not solve the problem of bad documentation or bad libraries. Points to make his case are weak. Better autocomplete? Reliable libraries? The library still compiles to JS and you can still use TypeScript naively and incorrectly and ignore typesetting altogether.

TypeScript doesn't solve the problem at all. It merely adds another layer of complexity/knowledge to a Library that still compiles to JavaScript. Write it in JavaScript, deliver it in JavaScript. If your documentation and implicit typesetting is giving you pains, then you should revisit what you have written and how you've built your library. Not switch to something that tries to enforce better behaviour.

[+] andrewingram|10 years ago|reply
I've recently started using Flow alongside Nuclide IDE (a Facebook-developed suite of Atom extensions), which allows me to easily see the type of a given variable.

What's nice is how much types can be inferred from just a handle of type annotations. My editor can start pointing out potential bugs at the cost of relatively little effort on my part, and that's a good place to be.

[+] tommyd|10 years ago|reply
How are you finding Nuclide? When I tried it a few months ago it seemed pretty slow and unstable, and eventually ended up consistently using all my CPU after a while. There wasn't a great deal of documentation/help setting it up available (true of Flow as well to a lesser extent), which was why I chose TS at the time, but am definitely interested in seeing how Flow is progressing.
[+] phazelift|10 years ago|reply
I was kind of frustrated for a while with the broken type system of Javascript, as well as with the lack of easy type checking. I then wrote a simple small library to make my life a little easier. It's called types.js, in NPM as well..

Changing my entire code to TypeScript just feels a bit over the top to achieve only static type checking. I now only dynamically check if needed. I believe there are so much worse and important problems we are dealing with as Javascript developers today that need attention.

I really believe WASM will become the base for a great new language that eventually will make Javascript, TypeScript and so many others deprecated, solving a zillion problems at once.

[+] crudbug|10 years ago|reply
People should embrace the functional expect of JavaScript. I am starting to see ES6 classes flying around everywhere.

Flow allows you to add Types by following Progressive Enhancement [1].

All libraries should support Functional APIs.

[1] https://en.wikipedia.org/wiki/Progressive_enhancement

[+] highwind|10 years ago|reply
All x should be y is a bad statement to make, especially if you are an engineering. Every problem domain is different. And every choice has pros and cons.
[+] jfe|10 years ago|reply
In my limited experience working with JavaScript, I've found the lack of the following to cause more problems when writing modular, reusable code than the lack of type annotations:

* a single, definitive method for creating namespaces without using a framework or library

* a single, definitive method for defining classes and using inheritance without using a framework or library

* a single, definitive method of allowing async functions to modify the state of an object without having to declare that object in the global scope, without using a framework or library

If these problems are already solved, please let me know!

[+] al2o3cr|10 years ago|reply
Alternate title: "Everyone else should invest the effort to support my use of TypeScript"
[+] BinaryIdiot|10 years ago|reply
Absolutely not. This is the opposite of what you should do in my opinion.

If you're writing an API to be consumed in language X then you need to write the API itself in language X. This will help you capture and handle edge cases, language idiosyncrasies and other similar issues the way you want.

Using a different language that gets transpiled into a target language also increases your surface area for bugs because now you have to worry about typescript and JavaScript bugs. After using CoffeeScript a few years back and spending HOURS debugging issues in its transpiling to JavaScript I decided it just wasn't worth the hassle. Besides JavaScript, while not perfect, is pretty damn good.

I love the idea of type script but transpiling it down into a language that isn't as type strict just seems silly to me. Now when it can be compiled to WebAssembly? Count me in.