Hacker News new | past | comments | ask | show | jobs | submit login
JavaScript libraries should be written in TypeScript (staltz.com)
386 points by ingve on March 16, 2016 | hide | past | favorite | 275 comments



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...


> 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...


That does help a lot and was a long time coming.

TS is a little harder to get started with for a few reasons. For one, it simply does more, with features like interfaces (which "sort of" exist in Flow), and public/private accessors.

One distinct advantage of Flow is that it is not a build step, but is more like a linter. I like this - it doesn't re-invent the wheel, so you don't have to choose between having the latest features or being fully TS-compatible. On the other hand, Flow's typechecking is far less complete, and it still uses its own home-rolled parser which occasionally has issues parsing certain ES2016+ features, such as decorators.

If I were starting a project from scratch, I would likely use TS as it's simply more complete. But if I were migrating an existing project, Flow starts paying off right away and is easy to integrate.


As you mentioned, Flow not being a build step seems to be a big win to me. A lot of different tools use or encourage you to use babel and babel is ahead of TypeScript in ES6/ES7, http://kangax.github.io/compat-table/es6/. If you use TypeScript your chain suddenly becomes much slower/more complex.


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.


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.


He mentioned "contracts." You can throw off the shackles and use the `any` type internally, but at the very least your public interface should have a well-defined contract. TypeScript is one [very good] way to achieve that and it even spits out machine-readable "contract summaries" for you (.d.ts files).


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.


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.


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".


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."


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.


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."


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!


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.


Which leaves me wondering why I'd use Typescript over sticking with ES6, especially with tools like Babel making many future features available right now and libraries like React actively making use of them.


> especially with tools like Babel making many future features available right now and libraries like React actively making use of them.

You get all of this with Typescript, as well as optional types. If you're writing any Javascript at all, technically you're already writing Typescript.


People told above, think of TS as a strong linter over normal ES6. Static typecheck is often very nice.


You shouldn't. My comment was in regards to readability of typescript vs coffeescript vs es6-javascript. If you don't want the added benefit of type-checking with minimal overhead, don't bother.


Except this really isn't an issue for TypeScript, it reads that close to JavaScript.


It's not about reading, it's about the tooling you need to set it up. JS initial strengh was ease of dev for beginers. Throw in a transpiler, a dependancy manager, a package manager, a bundler with FS watching, and source maps and what you got is wall for the very same type of dev that were producing all those fantastic jQuery plugins 10 years ago.

And actually even for me.

I do know how to install and use all those. I just don't want to take the afternoon to do so.

Why ?

- Only one project out of 5 are big enough to justify it. - The stack will change in 6 months; - I will need to train anybody who gets on board, and document it, and maintain it. - All this tooling integration is terrible in JS, because they are an agglomerate of stuff we are stacking after the fact to compensate JS bad initial design. The same stack for any other language is 10 times easier to setup and maintain (the stdlib is here for you in Python, you don't need to load a deendancy to generate a uuid), or it's just here out of the box (type hints ? embded in Php) or event completly uneeded (nobody use transpilers in Ruby hence no source maps, etc).

So yes, it's annoying.


> It's not about reading, it's about the tooling you need to set it up.

npm install typescript -g

This is the only addition on top of vanilla js, which is what you should be comparing with instead of the massive crap of build-tool-of-the-month. All said and done, if you're using those build tools in typescript, you'd be using them for javascript as well.


No.

First you need to install node.

Then you need to install typescript.

Then you need to setup something that watch the typescript files and transpile them when they change. Because no, running a command everytime you change a letter in the file is not acceptable.

Then you need to integrate that in your static assets pipeline (minifiers, linters, git hooks, i18n extraction, whatever). Because files changes and are generated on the fly, and you probably use a framework that already interact with them in some way.

Then you need to make sure it's part of your deployment process, including continuous integration. Because the typescript command now must be in your builder scripts, travis files, docker container, etc.

Then you need to setup your browser to read the source map. Because debugging a transpiler without a source map is hell on earth.

Then you need to setup your IDE to understand typescript. Yeah, most editors don't understand type script.

Then you need to document that, and train yours colleagues. They don't have the same OS, versions, editors, experience than each others.

What's that, you spend 2 hours trying to help a new commer in your team on skype to find out you just don't have the same version of type script ? What's that you have a concurrency problem between several FS watchers ? What's that, somebody commited the transpiled files on the git repo by mistake and now some edge case made the travis build fail ?

Saying "it's just npm install" is disrespectful, at best. It's NOT a 5 minutes job. It is work.


>First you need to install node.

The article doesn't really apply to you if you aren't using node. If you're only using a script tag, it will have to be consumed as javascript anyway. Any library that is written in typescript will have a transpiled javascript version available to you, or there would be no point in writing it in typescript.

> Then you need to install typescript

See above

> [more irrelevant complaints]

See above.

> Then you need to setup your IDE to understand typescript. Yeah, most editors don't understand type script.

PHEW. This may have been my most difficult google search of the week: http://lmgtfy.com/?q=typescript+editor+support&l=1

> Then you need to document that, and train yours colleagues. They don't have the same OS, versions, editors, experience than each others

If you're have issues surrounding this, typescript should be the least of your worries.

> What's that, you spend 2 hours trying to help a new commer in your team on skype to find out you just don't have the same version of type script ?

Heaven forbid you have an onboarding process that is documented and methodical. My entire team runs the same version of node. We keep track of issues surrounding operating systems and IDEs so we have reference material when others bump into similar issues. If you're not doing this, there's no way in hell I'd want to use anything you're producing.

The article and commentary is about PUBLISHING libraries, not consuming them, and it's not about eliminating javascript from private repositories. If you're publishing an open-source library and aren't using node nowadays, color me impressed, given that most of the major testing frameworks are built around node. Even jQuery has required node to contribute since 2011 because of that. I have struggled to find a popular front end-only library that doesn't utilize node in it's development process. Those libraries HAVE to include a js file, since that's how the the browser consumes it. So... the world kept on spinning after you made a mountain out of a pebble.

Failing to read/understand the article, and subsequently huff and puffing a list of irrelevant objections is disrespectful, at best. Clearly nothing here applies to you, and you've managed to take that as an opportunity to point out how inept your team is. Congrats.


I'm a freelancer, I change team every month or so. You have been spoiled with your team members, working only with professionals that know the JS ecosystem and have defined process and a good management.

You think that most people publishing lib are unit testing them ? JS is the language with the least unit tested code I know. You think people writting JS use node ? Man, you need to quit working for L.A. start up, there is an entire world out there that is learning about stuff as basic as AJAX calls and making libs anyway because they have knowledge about their job they want/need to share.

I work with american clients right now. Well, they are working on an open source code base they got from Africa. The code is not remotly close to your fancy standards.

I worked with people working in the geography field 2 weeks ago.They learned Angular JS. Choosing between the minified and the non minified file was the struggle here. No, they didn't have Node installed. They don't even know what it it. Yes, they will produce JS libs, they have knowledge only they got, and they will share it.

I worked with a friend in porn 3 month ago. He is still using jQuery and manual JS files. Because it works, because it's simple. He is never going to use type script, he doesn't even have the time to read about it. People reading HN are an exception, a microcosme. Yes, he published a lib to generate visual hashes for passwords.

"Everybody should be using typescript, it's so simple" clearly ignore completly the heterogeneous world we work in.

It's pretentious. It's condescendant.

Congrats.


> I'm a freelancer, I change team every month or so.

This isn't an excuse to be disorganized or fail to do a proper onboarding. You're justifying incompetence.

> You have been spoiled with your team members...

I've never worked with shitty people. Either I'm the luckiest idiot in the world, or I actually take the time to do research before accepting job offers. I'm leaning towards the latter.

> You think that most people publishing lib are unit testing them ?

One's that people use? Yes. If you aren't unit testing published libraries, you're doing nothing else but shitting in a bucket and tossing it on the street. If you're using those packages without validating them, you're the one licking that street. If you have a wall of script tags of random libraries used to do each piece of your application, it's nothing better than copy and pasting from stack overflow. All you're doing is stacking wood for an eventual bonfire. I just took a minute to look at the libraries we use. All but one has tests. Funny enough, we aren't actually using it. Thanks for helping me clean up my scripts. So... I guess my life tip is to pick better libraries.

> JS is the language with the least unit tested code I know.

It's also the most tested one I know. Oddly enough, it's the most used language in the world. Weird how numbers work.

> You think people writting JS use node ? Man, you need to quit working for L.A. start up

Yep. I actually work in NY. Maybe there's a serious difference between the two cities. From what I see, companies that last more than 3 months tend to have even the most basic of organizational skills. Companies that don't last 3 months typically don't publish packages. But hey, to each their own.

> They don't even know what it it.

I'd love a list of the companies you've worked for so I can avoid anything they've built. As you've said, ignoring the ecosystem we work in is ignorant.

> Yes, he published a lib to generate visual hashes for passwords.

so... a single function? Wall of script tags, bonfires, failing application, debugging hell, over-dependence, etc. As a freelancer, I have a tip for you that might save you some time and increase your income. Spend less time googling for packages and spend 10 minutes building them.

> "Everybody should be using typescript, it's so simple"

I'm not arguing for the first part. I'm arguing for the second part. Simply put, if a person publishing a package doesn't understand the whole javascript ecosystem (node included), I have no interest in consuming their product. Maybe it's just me, but I don't enjoy spending time debugging a package that I have no control over. If it's internal, I can yell across the room to the person who built it (and marked it with their contact info. You built it, you own it). If it's external, I expect to be able to run their tests (hence why we all have node) so I can easily find a point to debug from, and submit an issue if it's truly an issue from them vs. me. If it's me using their api wrong, that's the perfect example as to WHY you should use typescript. It's self-documenting, so I would be able to see the issue quickly without running their tests. Again, as a freelancer, I'd expect you to want to save time.


I love the irony in this comment (and a couple of its siblings).

It's as though crazy javascript tooling is so deep into the bones of javascript developers that they can't even tell when they're using a tool. I expect you were genuinely sincere in your suggestion.


You're criticizing a comment making an assumption about javascript tooling, on a thread specifically ABOUT javascript tooling? If you aren't using javascript tooling, wouldn't a change in that tooling have no impact on you? Seems like an odd criticism to me.

Regardless, the only thing I mentioned was npm. I don't consider node/npm to be "crazy javascript tooling". So yes, I was genuinely sincere.

"In order to build jQuery, you need to have the latest Node.js/npm and git 1.7 or later. Earlier versions might work, but are not supported."

Welcome to [1]2011, where the most prevalent front-end codebase requires node and it's package manager to contribute. Feel free to peruse the countless other commonly used libraries. Maybe you can point out a widely used front-end codebase that doesn't use node/npm/git? The only one I could find was BabylonJS, which uses bower. Conveniently to my point, bower is dependent on node/npm/git.

Writing code in a text editor and saving it with the extension .js makes for a javascript file. We know that. Using that file in the browser means using some a <script> tag. Whether its from the server or through a cdn, that script tag contents/url will still have to be in javascript, even if you used typescript to develop it. No negative impact on text-editor user-land.

[1] https://github.com/jquery/jquery/commit/d503845d0cf45632c0d7...


For what it's worth, jQuery doesn't need npm. You can grab the .js or link it from the CDN as you prefer.

https://jquery.com/download/

I haven't come across any .js library that doesn't offer the same.


Right, but that link won't change even if they switch to typescript, which is where my point lies. The benefit comes to package contributors, consumers looking for accurate documentation, and anyone that uses a build tool/IDE/or even a text editor with basic syntax highlighting. All of this while having no negative impact on people who only click your link.

I'm not encouraging everyone to adopt it. I just struggle to see any objectionable aspect from anyone that is solely on the consumer side. Basically, if you aren't using any tooling, the world will keep on spinning.


Wait, you mean I can start up a brand new Windows machine and type "npm install tsc -g" and stuff magically happens?


Visual Studio 2015 and Visual Studio Code both support npm. I don't even think you have to type "install", I think it's just a matter of listing "tsc" in your package.json file.

(I haven't tried it myself yet, but I just got back from VS Live in Vegas where the ease of package management in VS 2015 was brought up in several sessions.)

Check it out here: http://webtooling.visualstudio.com/package-managers/npm/


"On top of vanilla js" meaning node.

I understand what you're saying, but it's completely contextual. The title of this article is "All javascript libraries...". Maybe it's just that I'm not a front-end-only developer. I have no clue about the development process for exclusively front end libraries, but I don't see many people develop them without node/npm. Hell, JQuery has a package.json, and:

"In order to build jQuery, you need to have the latest Node.js/npm and git 1.7 or later"

https://github.com/jquery/jquery


You don't need tooling to use libraries written in Typescript. NPM libraries distribute the compiled source.


WRT Ruby, there's actually Crystal and InfraRuby (off the top of my head) that both seek to add typing to Ruby. For Python there is mypy.

> Only one project out of 5 are big enough to justify it.

No, any library author could benefit (strong set of features, added type safety, additional usability for TS users from proper .d.ts files). Key point here, TFA is about libraries not projects.

>The stack will change in 6 months;

TypeScript has been around longer than 6 months and has only gained traction.

> I will need to train anybody who gets on board, and document it, and maintain it.

Learning TypeScript takes a day at most. And if you really need to justify that lost time, just remember that outside of types, everything else is just ES6/ES7 features.

Document it? Ever heard of self-documenting code?

Maintain it? It sounds like you really don't know what TypeScript is about.


you say "only one project out of 5 are [sic] big enough to justify it", and then complain that the perks that tooling provides aren't part of the core language. do you see the inconsistency there?


Except it really isn't. As soon as you convert to .ts you'll get a boat load of errors and have to re-declare your types and input parameters as vars for TS to ignore them. Also not sure what would be the point of using pure javascript in this context other than marginal benefit of a compiler detecting javascript syntax errors. Not arguing pro or against TS just pointing out it's not the same as using javascript


Maybe we'll agree to disagree but this [0] doesn't read very close to Javascript at all.

[0] https://github.com/Microsoft/TypeScriptSamples/blob/master/t...


That does though. Skip to line 120 where code is actually written, and it's ES6. The top part is type definitions, which could just as easily be thrown at the bottom. I'd argue it should for exactly this reason.


It reads closely to JavaScript. But it is not.


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.


Simple solution - offer the compiled file in the library. Everyone wins.


This is the default way of doing things on npm that I've seen.

http://stackoverflow.com/questions/29738381/how-to-publish-a...


Then just compile the library and everything will read like really well-written JS.


And then new transpiler language appears, with "real" type system, not java-grade. And everyone stops using typescript, treating it as outdated technology.


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.


It already appeared, and is called Purescript. It's great, and it's about as likely to gain traction as Haskell.


If there's any Haskell-ish JS language that will gain traction, it's Elm.


>it's about as likely to gain traction as Haskell

So rather unlikely?

Haskell has a JavaScript compiler as well, by the way (GHCJS).


> So rather unlikely?

He means it already exists and hasn't overtaken TypeScript's popularity.


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.


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!


But the typescript type definitions will still be useful. See e.g. https://github.com/sjrd/scala-js-ts-importer


Every 6 months


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.


> not java-grade

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


At that point, you can always transpile from Typescript to javascript or maybe even from Typescript to the new language.


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.


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.


Yes, I don't think I was clear enough but I edited a lot of points out of my post as it was far too long!

The biggest problems in any modern, large-scale JavaScript project are the build process and dependency management. If you are publishing a TypeScript library then it can be consumed either natively as TypeScript, or as ES5.

If it is being consumed as ES5 then your consumers lose most of the benefits of it being in TS. For them to consume it as native TS puts a fairly hefty constraint on their build process, namely that it must go through the TypeScript compiler.

That doesn't negate the internal benefits to your library, but Flow is another option that is a better fit if you are mostly interested in going with the prevailing wind. After all, that was the author's central argument as to why you should choose TS over Flow, and IMO it is quite wrong.


The article talks about TypeScript vs. Flow as well - TS has a lot more popularity than Flow currently, and it only looks like the gap is going to grow larger. Types also allows for auto-generation of docs that are guaranteed to reflect the current state of the code.

For a library maintainer, a maintainer can just release an ES5 version of the library when publishing via npm - the user then gets the benefit of choosing between TS or ES5. It can also simultaneously be released as ES6 if desired.

I should mention that it doesn't make sense for pre-existing libraries to migrate to TS (or anything) if it is already in JS and is a largely used library without a specific end goal that is to be achieved - the article is wrong about that, open source doesn't have infinite resources unfortunately.


> If it is being consumed as ES5 then your consumers lose most of the benefits of it being in TS. For them to consume it as native TS puts a fairly hefty constraint on their build process, namely that it must go through the TypeScript compiler.

Unless you're making changes to a TS library, there should be no need to build it and you can just use existing the built js files from the library.


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?


What does one miss out from Babel, given that TS is a superset of ES6?


It depends. The problem isn't so much what you might miss out on if all you are doing is writing a library, the problem is what limitations it places on consumers of your library.

The most obvious Babel plugins are JSX and Flow. If your library is using TypeScript then it cannot go through the same build process* as any downstream project that is using any Babel plugin. That means you need to publish your library as ES5 and the client loses most the advantages of your library being in TypeScript in the first place.

Also, Babel appears to be doing a slightly better job of keeping up with the draft ES standards, so if you want to use cutting-edge JS features (like async/await) that are on the standards track, you may need to wait a bit longer for TS adoption to get there.

I also think it's unlikely TypeScript is going to win out in the long run, so if you commit to TS now you're probably going to be rewriting in a few years. It's better to stick to standard JS where possible. The history of ES4 strongly suggests that TS is never going to become an ECMA standard.

* You can, at least in theory, do a two-stage transpile that goes through both Babel and TS, but IMO, nothing good is likely to come from such a setup.


TypeScript supports async/await and JSX (if you use the .tsx extension for your files), the compiler team has been extremely diligent and keeping up with new ECMAScript standards.


I'm not sure I understand what you mean by "the client loses most the advantages of your library being in TypeScript in the first place." Your library still exposes a more clearly-defined API by making types explicit. And saying that the downstream consumer doesn't get the benefit of compile-time type checking if they've chosen not to use type checking is...kind of a truism?


The problem is with the author's assertion that all libraries should be using TypeScript and not, say, Flow, or some other alternative that achieves the same goals, perhaps better.


Does Flow offer type definition files?


Yes. Also, there isn't a need to maintain a separate definitions file[1] if the library was developed as Flow-typed code. I've made a few small libraries[2] that were written with Flow-typed code, and are built so that the types are automatically enforced if you use the library in a Flow-typed project.

[1] A hand-maintained definitions file: https://github.com/facebook/immutable-js/blob/master/type-de... . Sure, it's nice as documentation, but that is a lot of redundant effort if you already have separate documentation, and types and documentation in the original source code too. [2] https://github.com/AgentME/contain-by-screen is one simple example.


I guess the point is that with Babel you can enable so called "stage 0" language features, which aren't in the spec yet but someone has created a Babel plugin for (e.g. decorators).

With Typescript, you can't do this, because the code has to pass through the Typescript compiler first, which doesn't support (most of) these features (e.g. it does support decorators IIRC) so will throw an error when it finds an unfamiliar language construct, and it doesn't have a plugin architecture like Babel, so you can't add them in that way.

One example is the spread/rest syntax which is sometimes used in React projects isn't fully supported in TS: https://github.com/Microsoft/TypeScript/issues/2103.

I should point out you can use Babel and Typescript, so the Babel processes the output from tsc (needed for using e.g. async/await at present, as tsc can't compile these down to ES5), but tsc has to run first to make the code into valid JS (on this note, I was surprised how easy it was to remove TS from a project - Babel will ignore most of the TS specific stuff such as interface and type declarations, as it already strips them out for Flow compatibility and the syntax is largely the same)


Babel is highly configurable and relatively easy to write plugins for.


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...


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.


I don't agree. Bad documentation is worse than no documentation. At least with no documentation, I start with the expectation that I have to figure everything out on my own.


Or... at least accept the pull requests that have them cough async cough


+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.


While not condoning crappy documentation, the intro is usually the important part. After that, I find stepping through code to be more productive than reading documentation, exclusive of massive frameworks which tend to be fairly well documented anyway.


Do you have an example which has stood out for you?


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.


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.


+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.


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)


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.


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…"?


What's a "big" JavaScript library? How do you know how widely adopted your JavaScript library will be?


Regardless, it's difficult to think of any situation where a All _______ should use _______ is really justified.


It works for "people" and "common sense".


Depends on what you define common sense as and the context you are using it in.


All APIs need good documentation to be good APIs. If you're not providing good documentation with your API you're doing your users/consumers a disservice. Using a tool (TypeScript/Flow/whatever) to ease the pain of providing that documentation is in the best interests of an API developer since it reduces the friction of having to write the documentation by hand. Also, in this case, good documentation is not just documentation for the programmer that is consuming the API, but also the IDE within which the API is being consumed.

I'd say in this situation the title is justified.


All libraries should use input validation to avoid RCE and other attacks

All software that handles sensitive data should use transport encryption & encryption at rest

All software that uses encryption should use thoroughly vetted professional crypto

All computer users should use backup software


It's another click baity title like "Why we stopped using [popular X] for [less popular Y]", "[Popular X] considered harmful", "Why you shouldn't use [industry standard X]" etc.


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.


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.


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.


I had the same problems when I tried it roughly the same time as you, but I tried it out again this week and it seems to be working much better now.


+1 I just give a second chance to Nuclide + Flow, and works great


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.


Try Flow, if you haven't yet. It's not as complete as TS, but it gets out of your way and requires minimal investment. I find that the `(foo: string, bar: number)` annotation style is just far more readable than e.g. JSDoc. You don't even really need to be running Flow (babel will strip them), but it's practically free - why not.


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


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.


This. Qualifying with "All" rejects all the cases where the statement might not be true for unforeseen reasons. Disclaimer: I generally agree with the OP despite the presumptive title.


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!


The one about classes is solved by not using classes. Prototypal inheritance works well (and besides, most implementations of 'class-like' behaviour are using prototypes underneath anyway)

I'm playing a bit of a devil's advocate here ;)


ES6 provides solutions for #1 and #2. These will replace the fragmented existing solutions.

I'm not sure I understand #3. Closures?

1. https://babeljs.io/docs/learn-es2015/#modules

2. https://babeljs.io/docs/learn-es2015/#classes


Alternate title: "Everyone else should invest the effort to support my use of TypeScript"


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.


Have you used TypeScript? Try it out for a month or two on a real project.

It's the best thing that has happened to web development in recent years - it improves Javascript in a completely compatible and future proof way.

The most amazing thing is that Microsoft created it. It's the polar opposite of Old Microsoft - standards are being followed (not subverted), it's simple pragmatic and has no lock-in.


I love Typescript, I do all my javascript coding via it.

However, Though I wish it were, Typescript is NOT currently suitable for defining modules for external consumption. The problem comes down to no effective means of publishing the typings of your project and your project's dependencies. For example, if your project uses Promises, you might choose to include a definition of those promises, or (worse) reference a Promise typing you found on DefinitelyTyped. This will work fine for you, the publisher. But any consumer of your project will be rudely greeted with typing collisions: Things like "The interface 'Promise' already exists in es6.d.ts"

There needs to be a solution to this module publishing problem before people can seriously publish modules (using NPM) using Typescript. Unfortunately, I have been tracking this issue and there is no timeline for resolving it, mostly due to too many different module systems, and handling module publishing being outside the design-scope of Typescript.


typings[1] does exactly that as long as people start publishing their definitions (which is kind of the point of them). Relying on un-versioned ambient declarations is what breaks things, not having dependencies.

[1] https://github.com/typings/typings/blob/master/docs/registry...


thanks for the link. I'm partially aware of typings, but too into my own implementation right now to consider switching fro definitely typed. I'll give it a try and pray it actually can let me ship an OSS project!


For a quick and small example to see it in action:

npm init && typings init

npm install debug ms --save

typings install debug ms --save

debug is dependent on ms, so in node_modules you have:

|-ms

|-debug

| |-ms

typings/main/definitions will have

|-debug

| |-index.d.ts

|-ms

| |-index.d.ts

It makes up for this file structure by declaring modules named in a file-like structure so the entire dependency tree is self contained in one file, while only exposing it's own typings through the final export declarations "debug" and "ms". No stepping on toes. Best to see for yourself, it would take a bit to write down.

As a point of info, it only works when people start adding versioning to the typings registry itself. debug and ms are both versioned in the registry, which is the only reason their dependencies are correctly managed. DefinitelyTyped ambient declarations will still break things. Until those are gone and everything is versioned, you'll still need some hacking depending on your dependencies. That being said, I've seen the issues start to fade rather quickly given the short time period I've been using it.


TypeScript has support for namespaces, and `import` gives you a lot of flexibility. If these aren't sufficient to handle the problem you describe, can you explain how? Can you post a link to the issue you are watching so we can see a better description of the problem you're running into?


Here's a scenario: You write a library that uses Promises, and use bluebird.d.ts for that definition.

For someone to use your library, they will have to download bluebird.d.ts manually and include it. if you (the lib dev) include it yourself, then any other definition of Promise (including if the user has their own bluebird.d.ts definition included) will cause typing collisions.

As someone mentioned, the Typings project might solve this, but there isn't very good communication on this project and the problems it's supposed to solve.


Is TypeScript really future proof? I mean unless types, exactly implemented as they are in TypeScript, will become part of the spec, we can't really call it future proof. Also how is it compatible with anything, JavaScript is compatible with TypeScript, since TypeScript is superset of JS, but it is not compatible the other way around.


Yes, it is. Compiling TS just removes type annotations; the compilation output (.js) is as readable as your original .ts. It has the same structure, same indentation, same variable names, same whitespace, same comments, same everything. This also makes debugging the code in the browser very easy.

TS does not add any semantic features, it only adds type annotations. Which it checks at compile time, and then removes. That's it.

Want to switch away from TS? Compile all your .ts files, save the .js, check that into your repo and continue from there.

(As other commenters sort-of pointed out: you will need to keep Babel in your pipeline.)


Interesting, I never 'considered' that. It's basically a thin typechecker linguistic layer. A variant of gradual typing.


Thanks for the concrete description. Can I still use dynamic constructs such as string subscripts to associative arrays and code generation via eval()?


You mean in TS?

Yes. ∀ x: I can do x in JS → I can do x in TS

But, let's assume for a second that you couldn't: this thread is about TS being future-proof. I.e.: ∃ x: I can do x in TS & I cannot do x in JS? No, false.

This implies TS = JS. And that's the point: semantically, TS = JS.


OK, that's a good start. Is there a tool analogous to JSDoc for TypeScript that gathers the same docs without repeating the type info already in the code?


http://typedoc.io/ might be what you're looking for.


Thanks. Also, some informative samples of what TypeScript itself looks like.

https://github.com/sebastian-lenz/typedoc/blob/master/src/li...


Sort of. I don't recall the details from the top of my head and can't easily seem to find details, but I think we're seeing some divergence between Typescript's classes and es6 classes, though I think it's mostly syntactic.

Your code will keep working, but it may diverge a bit from standard JS; however everything will keep working, and I'm sure the expectation would be to move over the es6's syntax unless there were semantic reasons not to.

The Typescript authors are involved in the ECMAScript process, so I'm pretty sure that there won't be any surprising huge rifts at least.


I don't know why you're being downvoted. You're exactly right - there are a few tiny divergences between ES6 and TypeScript. In particular, try compiling some classes with Babel's strict compatibility mode and compare the output to TypeScript's output. There are several small semantic differences.

Also, there a few constructs in TypeScript that generate JavaScript code, like enum and module.

THAT SAID, TypeScript is basically ES6 + type annotations, and can certainly be used as such.


I'm hoping that Typescript will be willing to break backward compatibility when necessary to maintain its core advantage of being an assisted version of the standard rather than just another non-standard language. If Typescript gets out ahead of the ES standard and adopts a feature that is presumably coming in ES, but ES changes course and doesn't follow, TS will no longer be annotated, standard ES.

In this case, I'm hoping TS will just make the breaking change and go back to being pure, standard ES plus optional type annotations. Developers who use it would just accept that from time to time, this could happen, but it could probably be made a non-issue if MS just wrote another transpiler: oldTS -> newTS, for people whose choice of Typescript meant they had committed from the start to a system that would ALWAYS require transpiling.


It is, you just need to define a d.ts file. I was able to use plain jquery with typescript. Check out DefinitelyTyped. It's a project that makes it easy.


I have not used TypeScript personally, just read and try some demo of it.

But for me JS -> TS feels like C -> C++ evolution/Transition. For most of Unix utillies or even as complex as Linux Kernel, Apache, Nginx, C is good enough. In the hands of developers who master it, there are no C++ equivalent.

For after look at the v8's C++ code, I can't imagine anyone would write that with C.

But when a new language's ego system is not mature enough, the development work flow can be a nightmare. I remember trying to use GWT to compile Java into JS. The demo works and looks cool. But more often or not, I end up debug "The JAVA code" AND "The machine generated Javascript" AND "how that JS interact with different browsers" for something that is extremely trivial to do with one line of JS/JQuery code.

* Writing code is easy. * Debugging code is harder. * Make sure that code works on all the browsers are much harder.

* Debugging system with multiple languages (JS, TS, React, Angular, polymer, etc) + machine generated code is not easy.

* Integrated them all together to fixed all issues and make sure the final program will work on all browsers are > N^2, N^3, N^4 times harder?

I am old enough to admit, that is not a job for me. :-)


That's not my experience with TypeScript. To me, TypeScript feels like JavaScript, with a few bits that make it feel more like writing ES6 even though you're really writing something closer to ES5. The differences between C and C++ are much larger.

You're never debugging TypeScript separately from JavaScript.


I see the following code in https://github.com/Microsoft/TypeScriptSamples/blob/master/t... , For me, it is definitively not the JS I know.

  declare var _: {

    each<T, U>(arr: T[], f: (elem: T) => U): U[];

    delay(f: Function, wait: number, ...arguments: any[]): number;

    template(template: string): (model: any) => string;

    bindAll(object: any, ...methodNames: string[]): void;

  };

  declare var Store: any;

If there is bug in this code, I won't know how to debug it.

I have no clue on what the JS generated by it looks like.

If I have to ask some JS programmer with no TS experience to integrate this "ts library" into their app and make sure the integrated app works on all browsers. I would have no clue on the complexity of the task just as I have no clue on how complex it was to make the GWT generated JS app to work on all browsers.

If it is just a JQuery / JS app, I can have 80-90% confident on schedule and quality of the app delivery.

But that's me, like I said, I am too old... :-)


Just wanted to point out that that isn't the JS you know because that's just typing information -- it isn't generating any code at all, it's telling TS what the types look like for Underscore's external methods. This would be stripped out completely in the compiled code. The actual code that results in JS just below that is much more typical.


This is only a typescript definition. It only shows you the types that were already there - even before typescript was introduced. And if the JS developer was not aware that these are the accepted types for the functions then he obviously wouldn't also be able to use or debug it in pure JS.


Right, for the human there are still the English API docs to figure out the arguments and return values. These are the type annotations that TypeScript uses to let you know when you've misinterpreted the API docs, which is an incredible time saver.


I cannot vote this up enough. It really is such a different experience to developing in "plain" JavaScript.


It's so much more pleasant to write and maintain than wild, un(type)safe javascript.


Only problem is that it's not sound. That means that while it may provide static checking that your program is validly linked together, it can't fully prevent run-time type errors. And kind of like you can't be "a little pregnant", you can't be "a little typesafe".


Of course you can. Can't catch all the bugs; but can catch some of them. Which saves time and money. It doesn't actually have to be perfect to be useful and helpful.


I'm not saying it doesn't help. I'm saying you can't count on it the same way you can if you're working in a truly end-to-end statically typed environment. Even Scala's type system has its leaks, due to nulls.


Have you used ClojureScript? Try it out for a month or two on a real project.

We can do this all day ;)


You've basically ignored the OPs point entirely. Typescript is backwards compatible to JavaScript, ClojureScript most definitely is not.

Not that I'm agreeing with the post in question, but ClojureScript and TypeScript are very different beasts.


not sure what you're trying to say.


There are a lot of good JavaScript alternatives out there. This article sort of misses the point in what's good about alternatives existing - you can use any of them and expect decent interop with javascipt. A library in one is more exclusionary for all the other interests out there.


If Elm didn't also exist, I'd almost agree with you.


In an ideal world I'm sure a lot of us would love to work with Elm, but the reality in a commercial situation is often that the choice of language is driven by factors like: how widely used/well known it is, what the availability of libraries for it is like, how easy it is to hire developers with experience for.

This unfortunately makes languages like Elm and Clojurescript unlikely to be chosen in a lot of situations (e.g. as I understand it, the JS interop story with Elm isn't amazing, so you can't just use JS libraries with it).

Typescript is close enough to plain Javascript to not scare people off (I'd be willing to bet any JS developer could pick it up in a few hours) and can almost be considered in the same light as vanilla JS in such a decision, yet brings with it the advantages of a fairly decent type system.

As I've said elsewhere, it's definitely not perfect, but for developers in a position where other, more "esoteric" compile-to-JS languages aren't likely to be accepted, Typescript probably represents the best choice of bringing a decent amount of sanity and predictability to codebases.

(This isn't meant to be having a go at the parent BTW, it's just something I've been thinking about a bit and the comment jogged my memory!)


You can totally use JS libraries with Elm. Source: we do it all the time at NoRedInk, and we've been using Elm in production for our millions of users (as our go-to for all front-end work at the company, not just as a side thing) for the better part of a year now. :)

Details about our experience with Elm in production: https://www.youtube.com/watch?v=R2FtMbb-nLs


Just for the obligatory record: Purescript is basically "Elm evolved". Everything Elm does, Purescript does better (FFI for example is such a chore in Elm). Drawback: the learning curve is basically as steep as Haskell's.


My experience with Purescript/pulp was rather negative. Basic commands were throwing errors (pulp init IIRC) so I decided to not even consider it for anything serious.


The tooling is not perfect, that's absolutely true. I have to say though that any imperfections (which are going to get fixed anyway) are well worth it if you want a pure strongly typed language for the web. There's simply nothing better (except the full-blown Haskell-to-js compilers, like GHCJS and Haste of course).

I recommend you try again and file a bug or look for help in irc if something breaks again (although I've never seen pulp init throw an error).


My memory could be off (on which command failed). I think I still have the repo on my home machine, so I could re-visit and file a bug report. At the time I kept pursuing elm instead. Reports of better FFI with JS is why I had explored PureScript.


Update: The bug is with pulp server https://github.com/bodil/pulp/issues/133


Cool, does it work for you now?


That's interesting to know! Thanks


Being backed by Microsoft is another strong point of TS for some.


I can absolutely understand that coming from coffeescript (optional parentheses resolution... yikes).

But TypeScript is basically "Javascript + types + ES6". They call it an "erasing compiler" because it's not meant to do much but remove types/make ES6 code work with ES5.

There is one gotcha in name resolution when you're working in modules (if you are in a module a.b, and a.c exists, then c will automatically refer to a.c, even if a global c exists). But that usually gets caught by the type system. Lot less issues than coffeescript IMO


With `--target=es6` I'm not sure if the TypeScript compiler does any code transformation other than removing type annotations. So the chance of a 'transpiler error' is basically zero.


There are a few small things that still require conversion. But that is because Typescript also includes capabilities from ES7 (ES2016).

For example - currently in Typescript but only planned for ES7: https://github.com/jeffmo/es-class-fields-and-static-propert...

or Support ES7: exponentiation operator https://github.com/Microsoft/TypeScript/issues/4812

Typescript seems to be more like ECMAScript.next + types rather than ES6 + types.


My favourite thing they brought over from ES7 is async/await support via ES6 generators.


FYI, those are not ES2016 features. ES2016 only includes two small feature enhancements. They might make it into 2017, but if TC39 decides they're not ready, they'll just keep not including the feature in the annual spec revision.


Well the classes are converted into functions and it adds members to the prototypes, right? Or is that ES5 only?


What you mean is indeed ES5 only. ES6 has classes so it doesn't need to convert anything.


Oh. Cool. I didn't know that.


This reads like knee-jerk reaction from someone who's never tried TypeScript.


Criticism of that statement kind of hinges on the source material being solid enough to be taken seriously.

I mean, one of his main points is that everything written in JS should be written in typescript because it helps support typescript users. Another it is leads to better documentation, with no qualification of how that happens. It might make your intent more explicit to a reader of the source code, but that doesn't magically translate into documentation for an API user.

I personally find nothing good about trying to coercing a language into something it isn't and then transpilling it back and that article has no strong argument to make me feel any different.


> I mean, one of his main points is that everything written in JS should be written in typescript because it helps support typescript users.

I agree, that wasn't a good point.

> Another it is leads to better documentation, with no qualification of how that happens

The type annotations make the source self documenting in a way that doesn't go out of sync. There's also http://typedoc.io/


Typedoc doesn't keep up with TS versions. It's not really solid enough.


I've used it but never in a serious project. Like I said when it can be compiled into WebAssembly then count me in I'll certainly give it another shot. But until then I just don't want to deal with an, albiet probably rare but possible, transpiling bug. Plus there is huge value, in my opinion, in writing an API in the same language it's going to be consumed in. It lets me dogfood more effectively and write better, real world unit tests.


This is a biased and uninformative opinion. You haven't seriously tried it, yet you're already strongly against it and your biases suggest there are obscure transpiling bugs when I've yet to see any in practice. Had you used it for any length of time you would've noticed it catches several bugs which you otherwise wouldn't discover until runtime.

You're also waiting for the "magical" WebAssembly target that makes everything better, but instead WebAssembly would end up generating much more unreadable code that runs much slower for JavaScript which already benefits from highly optimized JS VM's in Browsers. It would also much larger in size as it would require embedding its own GC and be littered with numerous type-checks in order to support a highly dynamic language like JavaScript.


> This is a biased and uninformative opinion. You haven't seriously tried it

Correct. I wasn't asked for anything deep here and I already told everyone I haven't seriously used it...

> yet you're already strongly against it and your biases suggest there are obscure transpiling bugs when I've yet to see any in practice.

I'm against any tranpiling languages. I'm glad you've never seen any in practice. I have with CoffeeScript and it cost me a huge amount of time. But like I've mentioned in multiple threads here I understand that's an extremely rare edge case at this point in time.

That's not the only reason I've cited though. Transpiling adds in an extra level of complexity. I hate complexity. In order to test changes you have to transpile the code after your changes before you can test them. Yeah you can automate it but now I'm adding extra packages to my application only so I can run slightly different code than before.

No thanks. I like simplification. As simple as I can make something the better.

> Had you used it for any length of time you would've noticed it catches several bugs which you otherwise wouldn't discover until runtime.

Maybe? Since I've been using dynamic languages without runtime checking for over a decade I'd like to imagine I'm pretty good at finding most of these issues ahead of time. Still, it gets compiled into a less strict language so it's not a silver bullet by any means.

> You're also waiting for the "magical" WebAssembly target that makes everything better, but instead WebAssembly would end up generating much more unreadable code that runs much slower for JavaScript which already benefits from highly optimized JS VM's in Browsers.

I'm curious, why would you think it would run slower. According to the V8 team its start-up is faster and it uses the same engine so the speeds so be equivalent.

Regardless the code being "unreadable" for WebAssembly doesn't matter. Do you care that bytecode is "unreadable" or MSIL? I highly doubt you do. Same thing here. WebAssembly is going to exist inside and outside of web browsers. But we're also a long way off.

> It would also much larger in size as it would require embedding its own GC and be littered with numerous type-checks in order to support a highly dynamic language like JavaScript.

Wait, why? The V8's team's announcement said they still have to implement GC, etc for the DOM but that stuff would exist in the WebAssembly implementation itself and has nothing to do with your code.

WebAssembly is still a ways off but I'm excited at the possibilities.


> I'm curious, why would you think it would run slower.

Because every browser already has an integrated highly-tuned JS VM containing several years of advanced compiler research, including JIT's with runtime type profiling, type inference, type-specialized code generation that's highly optimized around JavaScript semantics in order to get today's JavaScript performance. That doesn't exist in WebAssembly which is a low-level statically-typed language that's effectively a compact binary form of asm.js for non-GC statically typed languages like C/C++.

> WebAssembly is still a ways off but I'm excited at the possibilities.

There is for C/C++ but none for running JavaScript which is worse in every way. WebAssembly is thrown around as some intangible moniker that will magically make everything better without understanding what it is and what it would take to implement a dynamic language with it, esp. JS which already has access to the best VM's the world's best compiler engineers can create.


I don't even use TypeScript but I don't buy your arguments at all.

> when it can be compiled into WebAssembly then count me in I'll certainly give it another shot. But until then I just don't want to deal with an, albiet probably rare but possible, transpiling bug

You really think a TS->WebAssembly compiler is less likely to have bugs than a TS->JS transpiler (which essentially just strips out the type annotations)? Yeah, no.

> It lets me dogfood more effectively and write better, real world unit tests.

I have no idea how these things are relevant. Why would adding type annotations to your code affect your ability to write unit tests. What does dogfooding have to do with anything?


> You really think a TS->WebAssembly compiler is less likely to have bugs than a TS->JS transpiler (which essentially just strips out the type annotations)? Yeah, no.

Absolutely. Why wouldn't it? Converting to a very explicit byte code type environment versus a language meant to be used by humans?

> I have no idea how these things are relevant. Why would adding type annotations to your code affect your ability to write unit tests. What does dogfooding have to do with anything?

The context of the discussion was around creating libraries for everyone to consume. If you're not testing your code as if it's being run from just JavaScript then you have a blindspot.

TypeScript is not only annotations. Check out the code it generates to support those annotations.


> Why wouldn't it?

Whereas TypeScript/Babel/etc perform relatively simple source code transformations, you'd have to implement an entire JavaScript engine in WebAssembly. It would almost certainly be slower and buggier than all of the big 4 JS engines.

> Check out the code it generates to support those annotations.

Ok, let's do that:

http://www.typescriptlang.org/Playground#src=interface%20Per...


Can you describe an example of a better, real-world unit test you have in mind?

Do you also advocate against writing ES6 and using Babel?


> Can you describe an example of a better, real-world unit test you have in mind?

Considering the output is a JavaScript library people will be using it in that context more than with TypeScript and many of the others. So I don't have a specific real-world unit test example but in general your unit tests have to test the various ways people are going to use your API from the target language. So you'll need to make sure it behaves in the expected ways with valid and invalid input.

At the very least I'd expect unit tests to be written in JavaScript to hit a TypeScript library to help eliminate any weirdness that could have been missed.

> Do you also advocate against writing ES6 and using Babel?

Yup. ECMAScript 6 is great but the support is still not entirely there (especially in older browsers) and many of the transpilings are not quite equivalent. Granted Babel is pretty high quality (minus their whole decided not to ship any transpilers in the default package anymore) and I would expect it to be close enough. But after being bit by CoffeeScript so many years ago I'd rather not deal with transpilers and use the real thing when I can.

Coding in ECMAScript 5 is guaranteed compatible with ECMAScript 6, most web browsers and most versions of node. So I look at it like this: why add the extra complexity just for a few extra, nice, syntax improvements?


> Plus there is huge value, in my opinion, in writing an API in the same language it's going to be consumed in.

Making APIs so that they are only accessible from a single language should be outlawed.


Do you ever minify your JavaScript before deploying? How do you know there are no bugs in your minified?


JavaScript, IMO, forces the developer to do a lot more defensive coding. All API's have contracts. An add() method that computers two numbers shouldn't expect a JSON object. For that matter, your method's contract shouldn't return an "any" for the same reason that you shouldn't expect "any" as its input.

What TypeScript does is remove the ambiguity of API development for front-end work. Considering I've worked in some big enterprise wide JS projects, TypeScript answers the question "Wtf is this returning?" which lessens my debugging time because I know exactly the type of the object being returned.

Your arguments are actually kind of moot. When you write in Java, you're really just boiling it down to an intermediary language. Should you write it in IL? Why not C/C++? Why not assembly? Shoot, just handout punch cards again and let's get to working. Abstraction isn't the enemy here, it's the value of the abstraction that gives value to it. TypeScript isn't so much an abstraction as a superset but it's static typing alone is worth 1000x over.


Defensive coding in JavaScript? That's absolutely not how most libraries are implemented.


If you're expecting one type and get another, you have to handle it, right? Documentation is important in JavaScript by virtue that code contracts are never enforced due to implicit typing.


JavaScript makes this process optional, and it only needs to go wrong once to become a problem.

Personally I saw over a million dollars lost and an entire team laid off after a piece of code started working with a value that was expected to be a number but wasn't.


> If you're expecting one type and get another, you have to handle it, right?

Depends. You could debate the same philosophy wrt C and null pointers. Should you check all your arguments to see if they're null, if the documentation/specification says they should never be null, or accept undefined behaviour and segfault?

In practice, most code assumes everything is checked, sanitized and used correctly at the outer most API boundary.


I disagree. The last letter of the API stands for "interface", which by the definition (a point where two systems, subjects, organizations, etc. meet and interact.) means you don't always have the ability to put a "same language" constraint on. By presuming the API will be consumed by something you have no control over makes you think about all the implications and types act as a guard of sorts.


At work our entire front end is TypeScript, and thanks to source mapping I've never had to look at JavaScript even when debugging problems. Typescript simply adds type annotations so you can get error underlining when you misuse a variable, and even more importantly (productivity wise) you get auto-complete members as you type.

Don't want types? Fine don't use them, and you have JavaScript code again.


What an odd argument. If you were writing a DLL for Windows would you expect the binary executable that's using it to be written in the same language?

Do you have an example of how writing something without types is supposed to help you capture edge cases? What are the idiosyncrasies of Javascript that can easily be caught in Javascript but NOT in Typescript?

WebAssembly adds massive layers of complexity that Typescript doesn't. You argue going from Typescript to Javascript is bad because, but Typescript to WebAssembly is good. One of this is vastly more complex and complicated, and it isn't TS to JS.


I do quite a bit of library development in TypeScript and one of the biggest wins is with new developers doing their first non-trivial bug fix or refactoring. The compiler has saved us from introducing all sorts of edge-case bugs because it catches downstream impacts that developers who are not intimately familiar with all of the code can introduce. A nice bonus feature is single line jsDoc comments replacing giant blocks of descriptive text.


Sounds like you've been tainted by your bad experience with CoffeeScript (which is very understandable).

Typescript is a whole different beast and I think the article makes great points for libraries. The more types the better.


APIs written in C seem to do just fine.


TypeScript is ES6 with types, so it is not a different language at all.


Not true at all. TypeSript has ES6 modules and its own module syntax. I don't know if it has improved recently, but using ES6 modules in our TS was nearly impossible if using type definitions using the old module syntax.


Couldn't agree with this more. Specifically, the lost hours due to CoffeeScript.


Typescript really isn't comparable to coffeescript


CoffeeScript has the worst tooling ever. QBasic in the 90s had better tooling than CoffeeScript: an integrated editor, debugger, compiler, type validation... let's give it all up to code in vomitscript.


Have you ever tried Atom? Its interface is written in HTML5 + CoffeeScript, and it targets CoffeeScript as the primary language. Tell the GitHub guys about tooling...

But besides, judging a language based on available tooling is akin to judging a CPU based on the computer casing looks.

For a real programmer, GNU Nano with appropriate highlighting should be enough. If a language calls itself "high-level" but makes the coding process hard without tooling, it deserves no attention at all.


A real programmer makes mistakes, and a real programmer automates tasks. That's what programmers are for.


Javascript IS pretty damn good. My IDE does a pretty good job at analyzing the structure of scripts.

So, I guess I have not yet felt the pain that "requires" a language upgrade. Unlike Java, which has really gotten to chafe me.

But then again, I started work back in 1985 using a scripted language (dBASE), with its own version of "eval", to make cute little UIs and reports that tied into the "real computer" / software (even if data swapping was swapping nightly batches of ISAM tuples, rather than REST calls). I also enjoyed using Perl in the 90s / early 2000s.

Then as now, the Serious People want you to wallow with them in the bondage and discipline of a Real Language, so you can type until your fingers bleed :-)

That said, I do write a lot of "JSDoc" in my code, and I resent the people who refuse to write Javadoc in their Java, because of course the types all make it crystal clear - NOT!


If it can't be compiled to JavaScript reliably then how do you expect it to be compiled to WebAssembly reliably?


Doesn't really need to be readable when compiled into WebAssembly though that I'd a goal. In that scenario it should work like any language in that you can debug in its native form.

MSIL and Java bytecode are not that readable but I mentally lump WebAssembly in the same group (though I know it isn't quite that). I feel like the end goal will be closer aligned to byte code than JavaScript.


I still don't really see the argument. It can already be debugged in its native form. I'm not sure how making the final product less readable helps with that.

WebAssembly is primarily useful from a performance standpoint.


RELIABLE, not READABLE.


This was my reaction upon reading the title of the post, having not used TypeScript. Mostly based on my experience and frustration with CoffeScript, mainly frustration at its existence.

But if TypeScript is an abstraction of Javascript that adds type security, then I'm pretty much all for it, even having been burned pretty often by unnecessary abstraction. I would say that the lion's share of my own javascript bugs spring from type uncertainty.


> "API to be consumed in language X then you need to write the API itself in language X"

I have to agree with the OP's point if your writing a library you should write it in the base language (common denominator). I work on JVM stuff and nothing is more annoying then dealing with a very nice library written in Scala, Clojure or Groovy and have it not work in plain Java. Plain Java on the other hand works fine in Scala,Clojure, and Groovy.

The above JVM languages compile to byte code (which I guess would be analogous to WebAssembly).

Thus I'm not sure if transpiling is as bad since Xtend (which is more analogous since its a Java transpiler) is very interoperable AND does not compile to bytecode directly.

So WebAssembly might end up being just as bad as the plethora of JVM languages that are sort of interoperable.


> nothing is more annoying than dealing with a very nice library written in Scala, Clojure or Groovy and have it not work in plain Java

I don't think the backers of Scala and Clojure make the claim that libraries written in their language will work seamlessly in Java, only that libraries written in Java will work in their language. The marketers of Apache Groovy, otoh, do claim code written in it will work in Java but from what you say that claim is false.


Sorry for the late reply but yes you can write some Groovy that will not work on Java (I'm trying to find when and where it happened to me... that could have changed).

The issue is that there are things you can do in JVM bytecode that you just can't do in Java and as the JVM develops along with these languages I imagine further interoperability.

You are right about the languages not making promises but there are plenty of library writers who disregard this. A fine example would be Akka and Finagle. Those libraries could have been written in Java thus minimizing dependencies and maybe even overall code size since they have to have a wrapper for Java anyway (typesafe did choose Java for typesafe config). But then again maybe Scala/Clojure buys enough that the wrappers are trivial. I'm just not sure how trivial interoperable wrappers for WebAssembly will be as I imagine WebAssembly will be a superset of what Javascript can do (or maybe not?).


Specifically regarding this discussion of typescript/javascript what are some edge cases and language idiosyncrasies problems you'd run into writing libraries in typescript?


I would use Typescript, but its type system isn't smart enough to handle the complexity of JS ecosystem. The other day I wanted to move my project to typescript, the first module needed ambient definition that didn't exist in Definitely Typed repo, it was quite annoying to create, and I am not even sure it's correct, then I wanted to type some parsed JSon that had a TYPE_NAME property with a string giving its type, it's basically tagged union and it doesn't exist in Typescript but only in Flow ... but flow doesn't work on Windows. http://flowtype.org/docs/dynamic-type-tests.html#tagged-unio...

So I completely abandoned my typing adventure.


I often use tagged union like interfaces in TS. It's definitly doable, but it might be a little more work than in Flow. For the definitions I do things like interface BaseInterface { TYPE_NAME: string }, interface DervicedInterface extends BaseInterface { ...content }. And to safely access the content of one or the other type I'm using user defined type guards like function isDerived(a: BaseInterface): a is DerivedInterface { return a.TYPE_NAME === ... }


Thanks, I didn't think of that, it's a little more work and error prone with functions and else/if code and less aesthetic than the switch/case that works with Flow, but I might restart my typing goal knowing that.


Yeah, the if/else cascades that you need when there are lots of cases are definitly not on the most elegant side. But maybe some support for type guards in combination with switch/case will follow. In can live with the current situation, because it isn't really better in most other programming languages without sum types (you mostly need some instanceof followed by a type cast).


Flow is being ported to work on windows and there are now builds out there for it https://github.com/OCamlPro/flow & the binary downloads http://www.ocamlpro.com/pub/ocpwin/flow-builds/


Thanks, I know but it doesn't work really well with server setup sadly.


I've been down this path before. I used coffee script on a few projects. Every time I have to go down that path I end up having to write more complex code just to do basic things. This blows up the project timeline when I could've done the same things in basic javascript in a few minutes.

I read lets discard the benefits of writing javascript as javascript in favor of something else because of a few people refuse to learn javascript. If you don't want to learn the language of the web then maybe just maybe it's not for you.

I think people coming to javascript from statically typed languages need to stop trying to fight javascript or trying to force paradigms on javascript that don't need to exist/never meant to happen and instead embrace javascript as it is and with an open mind.


There's too many dumb things in Javascript that should have gotten straightened out long ago.

I shudder to think of the countless man-hours that have been wasted working around and debugging issues caused by stupid design decisions in the Javascript language.


The Immutable.js API might be good, but the documentation is cryptic on a good day, awful on a bad one.


Exact same arguments that I use when arguing that any software above a certain complexity level and intended for a long life and maintenance should be written in a strongly typed language with working generics system.

Seems ironic that JS community is starting to come around to that finally.


It's more like a vocal minority rather then the "JS community". Apart from Angular && .NET people, Babel has the momentum.



I don't understand the lack of love for - or at least general community attention to - the Closure toolchain. Type annotations make a lot of sense for JS - they are native JS, they are optional, and generally conform to the jsdoc standards that people are used to. The Closure type system is pretty decent, as well. I have yet to see a really compelling implementation of a JS-like language that cross-compiles to JavaScript.


People spending their free time writing open source software should write it in whatever they want. There is no way anyone should be forced to comply with any standard when they are freely sharing their code. This article perfectly reflects my thoughts when it comes to asking open source authors to do anything: http://hueniverse.com/2016/01/26/how-to-use-open-source-and-...


This arguments boils down to "they are free persons" which is besides the point and doesn't tell us anything.

This is not about where you start from (totally free, their own time, can do anything) nor about whether they can be forced to do X or Y.

It's about what kind of community and software they (we) want to build, and what would be the best practices and suggestions.

Developers aren't forced to package their libs for npm distribution, write comments, ensure they play well with latest browsers, etc. either, but they do -- not because they are forced to, but because they agree that it's a nice thing to do.

FOSS developers do all sorts of stuff to make their software better for users already -- writing documentation, packaging for various platforms, evangelizing it, conforming to certain standards even when they don't personally use them or care for them etc.

Software development, especially community OSS is not about proving how "individual" one is, and doing everything for fun. It's also about wanting to contribute to a common cause and build some common foundations and best practices for a platform or language etc. Most projects agree to that idea, or at least pay lip service to the idea.

In this case, the TFA is not about forcing anyone to do something they don't want, so your reaction is besides the point. It's about suggesting what the author thinks is the better way for developers to do going forward.

>There is no way anyone should be forced to comply with any standard when they are freely sharing their code.

Force them not, but nudge them towards complying, or convince them to comply, yes, there are TONS of ways. Advocacy for some specific practice, like TFA does, is one.


If you don't want people to use or like your open source software, feel free to do whatever you want. I've got a bunch of open source shit on GitHub which is only there because it would cost me money to make it private.

If I actually want people to use it, I add documentation. And that's what Typescript basically is: rigorous documentation.


People make basic mistakes routinely with types. Even with very sophisticated type systems, like the one used in Haskel. There's evidence that in rare cases where people could have been "helped" by a type system, the cost of finding and fixing such a bug is far lower than using a type system to enforce correctness in the first place. You will write automated tests whether you're using a type system or not.


I am hesitant to start the whole typed vs untyped debate here, but this is exactly what your comment is highlighting. Where does all this evidence come from? I have recently started using Scala and while initially the learning curve was quite high, I have been so happy to have such a comprehensive type system.


I was wondering why no one has mentioned scala.js here. It would seem to have a good story to tell - strong typing and, according to the project site[1], good interop with JS. As a Scala developer with some front-end experience, exclusively with CoffeeScript (which I think is beautiful BTW, not a popular opinion in these parts), I wonder what are perceived to be the downsides, other than learning-curve and relative immaturity, of "client-side Scala"? I can imagine developers being adverse to working with a heavyweight toolset, but are there in fact interop (or other) problems?

[1] http://www.scala-js.org/


This is a more recent one: http://games.greggman.com/game/dynamic-typing-static-typing/

There's actually very little real research that has been done that proves or disproves whether static or dynamic typing is better. Anecdotally, I've spent most of my career using statically typed languages. One day I looked up and saw that I had spent most of the day trying to satisfy a compiler rather than having a compiler satisfy me. I've never really looked back. I program almost entirely in dynamic languages these days. Otherwise, I use Java, Swift and Go only when I'm forced to.


By adopting this stance, you are saying "The Javascript 'type story' is over. It's Typescript from now on"

I rather hope that is not the case.


While parts of the article seem over the top, I do agree with the basic premise of the advantage of type safe languages.

I struggle with the issue of type safety because while I really enjoy using Haskell on side projects, I find Ruby a giant mound of non-type safe glue that collects my ideas together into code. I use Ruby a lot.

I imagine that many JavaScript programmers like the lightness and malleability of their language also.


There's a big misconception that JS has zero typechecking. This is not true; rather, JS has dynamic typechecking. It turns out that when you're making an API for an external call, you will need to manually check the types of the incoming data anyway (and this is where I see 99% of JS type errors). This is something that JS is equipped to do fairly easily when necessary.

A typical type problem would be sending a float instead of an integer. Sending a float instead of a regex would not be a typical problem.Static types are necessary in less dynamic languages because they have multiple competing types which can't be distinguished otherwise (eg. all the integer subtypes) and they have structs/classes that cannot be dynamically modified. JS types are simple (number, object, string, etc) and very different in nature. In addition, this kind of error will be caught quite quickly with even the most rudimentary unit tests. Half-way decent docs where modules interact should solve the remaining issues. Running into type errors within the same file or two is probably symptomatic of a lack of composition.

Enter Typescript. It has one major positive in that it prevents some dynamic techniques that can tank performance (though performance graphing and reducing dynamism is probably a better solution). Because you cannot depend on everyone using typescript, all external APIs must STILL have dynamic type checking.

This leaves you with type checking within your own project. Typescript can be turned off anywhere a programmer wants making it unable to guarantee type safety. It adds a lot of extra typing and visual overhead. Unlike C# (where it gets it's type syntax inspiration), the types do nothing for the JIT because the JIT never sees them.

There's no reason for a modern type system to not be based on Hinley-Milner. There's no reason for 95% of typing to be inferred by the computer rather than forcing it to be typed out. There's no reason to use a system that's only good for the assembler when the assembler will never even see it.


Does TypeScript suffer from the same performance issues that Gradual Typing systems share [1], or does it sidestep these by virtue of being transpiled? Naively I'd guess not, which would mean that converting a library to Typescript would often impose a severe performance impact on JS users, but potentially afford significant gains for TypeScript users.

In TypedRacket, for example, using types in some (but not all) of your code can result in up to 100x slowdowns, until eventually breaking through into performance gains once most or all code is converted.

[1]: http://blog.acolyer.org/2016/02/05/is-sound-gradual-typing-d...


I wouldn't say that writing them it TypeScript would be good. But rewriting them in TypeScript at some point of their development might be good. Might expose some bugs (even some conceptual ones).

TypeScript doesn't feel like a boon when you write things with it because avoiding type bugs is further on the list. On the top of the list when you are writing something is figuring out what you actually want to write and what should be the APIs everywhere. TypeScript might make it harder to figure that out because you are getting invested too early in the shape of your interfaces. You'd get just yet another Java lib if you started writing in TypeScript. But once you have the right APIs there's no harm in formalizing them with bit of types.


IME, breathless superlatives such as "all x should be y" are almost never true. That said, the author did go to great lengths to support his argument.


Let's hope WebAssembly will help to relegate JavaScript to obsolescence and allow a productive and safe language to gain momentum. I also hope WebAssembly will solve the debugging (no DWARF) story universally.

Web browsers are one of the most popular attack vectors and hence would benefit from an APL-like rigid language profile for web applications. JavaScript is too imprecise and bug prone for anyone to use.


Javascript is evolving and it also has probably the largest number of developers in the world (both those working on JS VMs/tools and JS users).

Given that there are Cobol users still out there, it's entirely likely that JS will outlive both of us and maybe even our species :)

Plus JS is one profile away from becoming a very sound language. And it's not like it hasn't moved that way already (strict mode).


How so? Anyone can contribute to javascript but only a very small subset of javascript developers can contribute to the typescript library. Javascript will be around and in vogue as long as it's the ubiquitous browser language. Typescript? Who knows - some other language transpiling to js might be in vogue in a few months and then nobody would be around to maintain your libraries.


If you know JavaScript, I honestly don't think it would take more than a day to understand everything TS offers.


I like static typing and I like dynamic typing. Gradual typing gives you the constraints of both without the benefits of either.


I'm sympathetic to the worst-of-both-worlds problem, but can this actually be true? In the case of types, constraints actually are the benefit, right? Do you mean that if you don't have compile-time assurance for 100% of the code, the value of whatever % type coverage you have isn't very useful?

As someone who's evaluating Typescript and Flow for a team of JS devs, my intuition is that having some typed code would give you beachheads of type safety, which seems like a reasonable win and an incremental path to improvement. I'm curious if this intuition is incorrect from the perspective of those who have used gradual typing in the real world.


When in Rome, do as the Romans do.

If you're programming in a dynamic language, there are things that you do that would not easily fly in a static language. Things like tests for truthiness. On first blush, from a static background, something like "var p = x && x.y && x.y.z || w;" look terrible, but they're pretty standard ways of cascading through different options without causing null pointer exceptions in a language like JS. When you start introducing type constraints, you are committing yourself to getting rid of all those dynamic shortcuts.

Yes, shortcuts can sometimes get you in trouble, but they can sometimes get you down the road so fast that trouble doesn't have a chance to find you. That's sort of the tradeoff you make: we can be super-fast 90% of the time, at the cost of having difficult to debug problems occasionally.

On the other hand, when you have a requirement to have type constraints in your code, any other code you interact with has to also have type constraints. But in JS, that's not a lot of projects. There is the DefinitelyTyped repository, but it's incomplete and of unknown quality.

I had thought the same thing as you, "beach-heads of type safety". The problem is that dynamic code tends to infect static code. I eventually gave up on TypeScript after not being able to wrangle the combination of a few code generation and graphics tools. My project was already reasonably OO organized and not dynamic, but there was just no easy way to handle the boundaries of the APIs. To deal with it, I had to... start using the dynamic features of JS, giving up on the type safety.

For example, you can't do function overloading in JavaScript, because you don't have any information about types on which to differentiate functions. Well, it turns out that means you also can't do function overloading in TypeScript. The only reason Math.min works in TypeScript is because JS only has one number type, and it is 64-bit IEEE floats.

But some libraries in JS, and especially in DOM, do overload functions. You test the type of parameters at runtime and decide what each positioned parameter actually means. So if you want to use such a library in TypeScript, you need to have a type definition that uses Any for each of the parameters, meaning you've lost type safety and you're back to testing the type of things.

So it just leaves you in this limbo zone where you don't get to use the features of the native language that make up for it being so crappy, nor do you ever get to use the features of the transpiled language that promises to keep your code easy to modify over time. So that's what I mean about "worst of both worlds".

It's like trying to introduce rules on a group of anarchists: you're more likely to get burned at the stake than to make more productive anarchists. Or try letting a bunch of corporate lifers work without a direct boss: you're more likely to end up with a lot more donuts eaten than code written. What ES6 gets right is that it doesn't try to bolt on a type system into an ecosystem that just won't tolerate it. It has features for making it easier, less error-prone, more ergonomic to do things that people are already doing in ES5. In particular, people are already trying to make classical classes with inheritance out of the prototype-based class functions in ES5, so ES6 introduced a new syntax for just that use case that gets rid of all the repetitive and goofy "Object.create" and "MyClass.prototype.myMethod = function(){ blah blah blah blah }" stuff.


  So it just leaves you in this limbo zone where you don't get to use the features of the native language that make up for it being so crappy, nor do you ever get to use the features of the transpiled language that promises to keep your code easy to modify over time. So that's what I mean about "worst of both worlds".
I have to disagree with you on this - as you mentioned, you can always use the "any" type - you lose type safety but can then do more or less anything "type unsafe" you could do in JS... so to my mind it's almost more like the best of both worlds, you get strong typing wherever practical but you also have an escape hatch for times when it's too hard/impossible to type something.


Sorry moron4hire but you are underestimating TS types system.

You can write quite crazy expressions abusing Boolean operators and he successfully keeps the static type.

You can also have different method overloads signatures as long as you have a more general implementation that does the dynamic checks at run-time manually. Most of the time you can use Union types anyway.

The big collection of definition files for almos any JS library out there is a living proof of how is possible to describe statically almost any JS API.

Let's face it, dynamic languages are about laziness, not about 'unconstraibed creativity'


Laziness is the root of computer science. There is no virtue in hard work for hard work's sake.


paraphrasing some 20th century poet:

  from what I've tasted of typescript build times
  I hold with those who favor javascript
  But then I've seen enough of bugs
  To think that for frontend dev work typescript
  is also great
  and would suffice


Types are nice, but in the end a type doesn't convey all the semantics.

Types also add overhead. They can be also superfluous and unnecessary.

Getting your types in a application right and to gain the optimum from them is quite some work.

Over the years, i learned to appreciate more unittests over more types.


All of these "You should use X instead of Y" articles is really not much can debate because there is no perfect languages/tools where in this case, the author think TypeScript is better than JavaScript.

I stop find perfect language because there is none.


With WebAssembly making its rounds it would be cool if Javascript libraries are able to be written in C/C++ or other lower-level languages then exposed via an API. That way a lot of algorithms can be shared with native code-bases too.


That could more easily be accomplished if they had chosen a proper bytecode, like LLVM, even JVM. It's still possible, but WebAssembly is just a Javascript AST.


I just hope this will not be yet another point of fragmentation for JavaScript.

Not looking forward to not only having to use different build tools for all libraries I work with but also different pre-processors and type analyzers. Oh my.


Why would you? Just don't use those libraries that don't fit your work flow. This is where "framework fatigue" comes from, this word insistence on trying to include every project under the sun into your project.


Not sure if it's still true, last time I checked TypeScript it's not compatible with ES2015 as babel does, so I chose babel instead. It's good to have type safety, but there is also flowtype.


Is this like saying that JS is the moral equivalent of assembly language for the web platform, and high-level development on the web platform should be done using something like GWT and/or GXT?


It's open source. Get it?

Nothing all stoping, DIY, in fact encouraged. I agree .ts is great, and who ever desires a lib to be .ts, the only questions is: if you desire it, than make it so.


Nope, in fact you should not use JSDoc, and you should not follow Google's JavaScript standard, despite the fact they authored V8. Instead, you should follow a self-proclaimed "standard", that adopts unsafe practices such as not using semicolons, something that Google itself factually demonstrated as being unsafe. But even that doesn't matter.

Let's let humans do the job that computers can do faster and more reliably, like validating the types of variables and function signatures. Let's do everything by hand. Let's give control of our programming future to people that don't care at all about programming.


I think it is much more important that final apps -- not libraries -- are written in Typescript.


Someday soon JS libraries will be shipped in asm.js. Imagine jquery in asm.js.


There was project somewhere to do type-checking with JSDoc. Where is it?



Why not just using JSDoc for you library?


we probably should start doing new 'hello world' in ES6.


L All HN posts titles and comments should start with letter L!


types only matters if you are stupid


No.


> but transpiling it down into a language that isn't as type strict just seems silly to me

You obviously have no idea what you're talking about. Almost all statically typed languages get compiled to something much less type-strict. This is one of the reasons for writing compilers in the first place! Case in point: Haskell gets compiled to assembler. You can't get a much bigger difference between typing disciplines than that.


> You obviously have no idea what you're talking about.

This breaks the HN guidelines by calling names and turning an otherwise substantive (indeed, correct) comment into a personal attack. Please don't be nasty here, regardless of what the other person did or how mistaken they are. We detached this subthread from https://news.ycombinator.com/item?id=11297077 and marked it off-topic.

(Edit: I just noticed the discussion downthread— didn't mean to pile on.)


Good point, but is the first sentence necessary? :(


Are you implying that it's factually incorrect? Also, the word "silly" appeared in the BinaryIdiot's comment first. You have to be prepared for not exactly polite responses when you do something like this.


Incendiary language like "you obviously have no idea what you're talking about" is bad for the quality of your comment, and this entire discussion.

Not everyone is capable of looking past personal attacks like yours. It is the first step to a flame war.

You have something to say? Great. Just say it, no need to talk about how little the other person knows.

Aside from "two wrongs don't make a right," do you really feel that this is comparable?

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.

And..

You obviously have no idea what you're talking about.

If you honestly, in your heart of hearts, feel that both statements are ballpark same level of cordiality, then ok.


No, to be honest - and I really expected you to drop this argument, which is why I didn't bother elaborating earlier - it was an emotional response from my side. The first version of my previous comment didn't focus on the word "silly", it read something like this: "it may not be right to call the other person ignorant, but, for this particular person, it felt soooo good!"

Just as you say, we're human, which is why "not everyone is capable of looking past personal attacks". Moreover, what we regard as "personal attacks" varies from person to person. Personally, I felt insulted by the specific kind of ignorance displayed by BinaryIdiot in his posts in this thread.

I know I shouldn't have and I don't think the downvotes are undeserved. On the other hand, I obviously have my reasons for feeling that way; judging by the font color of many BinaryIdiot's posts I wasn't the only one.

I read through all the posts in this thread before posting. BinaryIdiot talking about how he experienced "transpiling languages" in the form of CoffeeScript and so he knows everything there is to them... That was excruciating. Him talking about compilation and compilation targets was similarly painful. One of the versions of my first reply to you read: "I've been hurt in enough ways and enough times [by people behaving like that] to develop a little bit of aggressiveness towards them."

In all honesty, the point about how compilers work was just an excuse. I suppose what I really wanted to do was to tell BinaryIdiot how wrong he is about some things, and how irritating it is for me personally (especially today!) to see him talking about programming languages, compilers, and whatnot without first investing any time on research.

Well, it's still wrong and I should have just ignored the whole thread.


Ok, I think you have a point and I blew the thing out of proportion. Sorry for that.


[flagged]


> Fuck you fanboy

You've been breaking the HN guidelines repeatedly. We ban accounts that do this, so please don't do this any more.

Following the guidelines means posting civil and substantive comments, or no comments.

https://news.ycombinator.com/newsguidelines.html


Maybe when it asks you to upgrade to Windows 10 this guy's picture could pop up like Clippy.


only siths deal in absolutes


This is akin to saying "Every C++ library should be written in Objective C."

EDIT:

Hey people down voting me; it literally is the same. C++ is a standard, JS is a standard. TypeScript is (like Objective-C) a compatible alternative.


"C++ is a standard, JS is a standard." seems to miss the point.

a better (but still imperfect) comparison would be suggesting to rewrite c libs in c++, given the latter's somewhat better type safety.


Absolutely not. Objective-C started out as a superset for C. Emphasis on 'started out'. It has nothing to do with C++. You can combine the two of them but they are hardly compatible. Messaging on the side of Objective-C vs. custom operators on the side of C++ being just one example.


Yeah and TypeScript has Types and JS doesn't. So, there's incompatibilities there too. Granted, the relationship is backwards so maybe I should have reversed the comparison, but it still stands. This was an asinine suggestion.


Oh of course, because it is strongly typed

Title just reinforces my belief that people have this feeling towards strongly typed languages like it's some kind of religious saviour and will try to preach it everywhere


All JavaScript libraries (!) should be authored in JavaScript.

All complex code that uses them should be authored in CoffeeScript.

Nothing more is needed.

P.S. TypeScript is M$ invention -> must burn in hell.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: