220 points · by svieira · 10y ago · 162 comments
Using TypeScript instead of JavaScript is such a productivity boost for a team developing a sizeable single page application, any other technical decision (which Framework, tooling decisions) is almost irrelevant relative to this major improvement.
TypeScript has ALL the properties that should make adoption a no-brainer:
1) Increases developer productivity, especially over long term maintenance timeframes. (My non-scientific, ymmv estimate is at least 30%)
2) Reduces production exception rate significantly
3) Can be adopted gradually
4) Full JavaScript ecosystem still at disposal
People seem to massively underestimate the benefit of a typed language in a frontend codebase. At gunpoint, I would rather have the backend in a dynamically typed language and keep TypeScript for the frontend. Chances are that the distance between your database and the API is not far, so static typing is not that useful.
However, if you have decided for a client side rendered application, your app is stateful, dynamic and probably quite big. Static typing really helps to avoid mistakes and increases the ability to refactor quickly and correctly by order of magnitude.
There are too many hardly ever visited code branches, and tests are very costly to write for an application where users can click a lot of things.
Python IDEs like PyCharm offer far superior tooling even without static typing, and Clojure is so nice I don't usually even need the tools.
There are a lot of impedance mismatches to deal with in the front end, (javascript to DOM, json to javascript, diversity of execution environments etc...), and I feel that when correctly used, dynamism the way javascript does it is a god-send.
All my core developments are in typescript, but in many situations it feels so magic to just do : myprop.undeclared = value and encapsulate the stuff in a knockout component written in typescript, while the situation would have caused a drama / major redesign in a back-end static language (C#, Java etc...). There are many valid scenarios (not resulting from a wrong OOP design) where this is very useful.
I'm actually amazed that people who designed Javascript got it so right. Static languages are great in the backend, typescript is great for the front-end and solved a real maintenance and Q&A issue by providing a level of typing and popularizing OOP in the front-end, but javacript is great for the web browser in general. Typescript is the piece that was missing, but this doesn't mean that javascript is broken, the elasticity of the language is a very powerful and elegant solution for the problems specific to the front-end.
And when I need to read this code later on and figure out what the shape of myprop is what do I do ? When I come across a function in a different file that touches that "unDeclared" property how the hell do I figure out what type it is, where it was assigned, etc. How do I find all references to that if "unDeclared" is a common word or is used on multiple types as a property name ?
JavaScript is just a nightmare to maintain - sure it might be easier to bang out the code initially - but good luck finding someone who will maintain that stuff once the author moves on. Hell - good luck coming back to your code base a year later and finding your way around that. From my experience most of non-trivial JS ends up being write only.
What exactly does “topology” mean in the context of programming languages? Are you trying to pull a Derrida (using fancy words without any actual meaning)?
> I'm actually amazed that people who designed Javascript got it so right.
Are you assuming that, even with a better language, the DOM's crappiness was inevitable, and thus we need a loosey-goosey language like JavaScript to deal with it? I doubt this is the case. Good languages make it easier to design good programs and APIs.
One benefit I've seen a lot is typing external services. A lot of code (both the frontend and the backend in say Node.js) tends to deal with calling external APIs, which would be dynamic in JavaScript and end up being quite loosely documented in the code.
With TypeScript, however, you can type in the JSON responses, which makes reading any code dealing with external services so much quicker. And these days with literal types you can even document that a particular property is either "magic_string_1" or "magic_string_2".
EDIT:
If you have static-typing and good unit-test coverage it's the best of both worlds I suppose. I tend to prefer duck-typing though which is sort of wedged in-between dynamic and static-typing in a sense. This however then becomes not a question of static vs. dynamic typing but of the language implementation of the type system.
In C++ for instance, the over-object-orientation is a pet peeve of mine when people define so many types and interfaces for this-and-that. I tend to prefer the "looseness" of template functions since you can pass whatever type in there so long as it contains the appropriate methods on the passed-in object. Such is static typing though so I'm digging myself into a hole from my original post :)
Now, a good static-analysis tool could catch issues on a dynamically-typed language in the same sense. Then I suppose the dynamic language becomes a pseudo-static language since a static-analysis algorithm is executed on the codebase. Since most build systems are set up to do: compile codebase; run static analysis to detect issues; run unit tests; run integration tests, it could theoretically be redundant step at compile-time doing static analysis when it's also done by an external tool. Just some stream-of-consciousness thoughts :)
Additionally, these are tests that you will have to tediously adjust every refactor since HTML frontends and it's data APIs behind it tend to change often over the lifecycle of a product.
From my experience, "only those tests" save you hours and hours of programming time.
That's not true. You can safely discard anything that tests something you've proven. A good type system doesn't only prove things for you - it also makes it easier to manually prove what the type system can't prove.
The problem is when the programmer doesn't know how much of his proof obligation is actually discharged by his use of the type system. (Hint: Not all of it!) And the solution is educating programmers, not replacing types with tests.
If you have a function, eg: (a, b) => a + b The only thing TypeScript will help you enforce here is that a and b should be numbers, and the function should return a number.
Except, the test for this will be something such: "given 10 and 21, return 31". So you're testing the return type already. TypeScript will ensure that you never pass a string to a or b, for sure, but you should not have a test for that (unless you literred your code with type guards and wanted to test those. Don't do that).
Now, unless the function above is your final, public API (where TypeScript/Flow will have the biggest bang for the buck and have the most value add), you're probably calling that function somewhere. That somewhere will be tested too, and the full test harness will make sure strings never end up there.
You'll never actually need to write a test: "Make sure this is a string", and the only vulnerable area is the top level API, and that is a responsibility of the caller.
For me, this mostly brings up the question of why the distance between data sources and front-end code apparently seems so big these days, and whether or not that's really an asset.
TypeScript 2.0 goes beyond that and begins to push the envelope on what type systems can do. Recently I've been loving the combination of discriminated union types and nullable types. It means that you can have code like this:
function myFunction(x: number | null) {
if (x === null) {
return;
}
console.log(x + 1); // x is now a number
}
The argument to the function is x, which is either number or null (that's what number | null means). But the if statement ensures it's not null by exiting the function, so by the time you get to the log TypeScript has (correctly) set the type of x to be just number!The types match up exactly with how you'd write the Javascript code. It's awesome and it just works.
Type systems could do stuff like that many, many years ago. I'm glad that you like these ideas, but let me assure you that TypeScript is far from pushing "what type systems can do".
FWIW, I didn't see any condescension there. I got more of a "Oh, you ain't seen nothin' yet!" vibe from it. Obviously, YMMV.
EDIT: Words
TypeScript is a pretty bad type system, but compared to Java and other mainstream ones, it looks like it "pushes the envelop".
Because of this, we're stuck with an half baked, crappy type system designed for mass consumption, and people adopt it with a round of applause.
That's no excuse to me an ass in response to your post...but it's part of why you'll see answers like that.
That people are actually using TypeScript could be the difference here.
As a side node, the FlowType system for JavaScript has had these features for over a year now, while TypeScript 2 is still in beta. These are the exact features which made us decide to go for FlowType instead of TypeScript 6 months ago. Happy to see that these two type systems now converge.
29 days ago somebody posted an unofficial Windows binary: https://github.com/facebook/flow/issues/6#issuecomment-22989...
function myFunction(x) {
if (x === null) {
return;
}
console.log(x + 1); // x is now a number
}
Edit: Or is this example being used to show that TypeScript now support multiple types including null in the parameter?I assumed that such feature would be available by default.
y = myFunction(1); // y = 2
y = myFunction("1"); // y = "11"
the ts version wouldn't allow you to compile myFunction("1")
The point of the example is that Typescript recently added support for non-null types, but is flexible enough to analyze where types have been further restricted by an early function return.
This thread, with people like you that seem to get it, is definitely making me want to try typescript.
function uhoh (x:string|number) {
if (typeof x === 'string') {
return x.length
} else {
return 'bar'
}
}
const a = uhoh('foo') //= string | number
const b = uhoh(3) //= string | number function uhoh (x:string|number) {
if (typeof x === 'string') {
return x.length
} else {
return 'bar'
}
}
function uhoh (x:string): number;
function uhoh (x:number): string;
const a = uhoh('foo') //= number
const b = uhoh(3) //= string uhoh : ((x : string) => number) & ((x : number) => string)
And get what you expect: const a = uhoh('foo') // : number
const b = uhoh(3) // : stringerror TS2354: No best common type exists among return expressions.
So at least it detects the problem. However the type inference algorithm should arguably return a union type here.
I find it good practice to always specify the return type of functions anyway. Then it will pick up cases where you return a type you didn't intend to; instead of just using a more general type it will tell you about the inconsistency.
I suppose the reasoning is that, when adding types to js, this is exactly the kind of bad behaviour you want to catch. But I'm not sure, perhaps there are just technical implications for not inferring union return types.
And the actual type of the const won't be `string | number` -- it will be `any`.
MaulingMonkey[1] has the right idea, though.
> if (a instanceOf SomeClass && a.someGetterOnSomeClassNotAvailableOnTheStaticTypeOfa != null)
Which is pretty awesome because it means you don't have to pollute your code with unnecessary casts.
fun myFunction(x: Number?) {
if (x == null) return;
print(x + 1);
}
if you don't check for null first the compiler warns.You can also do:
x?.let {notNullX -> print(notNullX + 1)}
or print((x ?: 4) + 1)
https://kotlinlang.org/docs/reference/null-safety.htmlIt really is an awesome language. Especially the delegated properties are wonderful. I use them to fill javascript-state for redux/react-native.
function second(y: number) {
return y + 3;
}
And you call second(x) from myFunction, the compiler complains if you haven't put the if() ensuring that null cannot pass to second()?But it goes further than that. TypeScript 2 adds control flow analysis, so adding to the top of a function that accepts a string or an array:
if (typeof someVarThatCanBeStringOrArrayOfStrings === "string") { // turn string into array }
any code below it can safely assume that the variable is string[], as well as the rest of the code that calls this function if this variable is returned.
(correct me if I'm wrong, y'all)
In your example, the JS interpreter will not throw an error when one provides a number (for example). Your code could break things. But why would this happen?
It's completely unrelated to TypeScript.
A number could be provided by the data, which in all likelihood is JSON from the network (eg: HTTP request or message queue body). Strongly typed languages will give you strongly typed data to protect you from this, but a dynamic language like JS doesn't afford you the same protection.
TypeScript doesn't mitigate this issue -- nor could it. TypeScript ensures your plumbing fits together, not that the sludge flowing through it won't cause a mess.
A strongly typed language will throw an exception before unexpected behavior can occur, JS on the other-hand will attempt to continue. It rarely happens, but since it does you can't say it safely works properly.
Now some of these people started to see some value in tool-based refactoring, and suddenly realize that types are not always bad. TypeScript undeniably improves the situation over JavaScript, with the caveat that it won't stop you shooting in the foot with the bad parts of JS. So now, types are good, nevertheless JS must stay.
I wonder how many years it will take for people to lobby for a clear break of JS backwards-compatibility, to use something that is not ad-hoc, has good tooling and a great base API, etc. Something where sorting number doesn't need additional extra care.
These usually start to matter when the team size is beyond 10 person working on the same part of the codebase. It will be interesting to see how this spans over the years. I bet the earliest "clear break of bad JS" will happen around 2019, with mostly linters and data flow analysis improving but hitting the eventual limits.
Uninteresting times, in a certain sense. I'm glad we have other tools to compete with.
Closure Compiler types are/were too verbose. It didn't support most module systems until this year.
Dart didn't provide an easy interface to existing JS libraries. Everything goes through a very cumbersome FFI. Also the only "tooling" was Eclipse.
TypeScript comes with a structural type system (with generics) designed exactly to fit existing JavaScript code perfectly, as well as a type definition scheme for existing code, as well as support for all current JS module systems (ES6, CommonJS, AMD). The tooling also comes in the form of an embeddable language service.
It succeeded because its a type system for JS, and not a compile-to-JS language for another ecosystem.
The difference is about the length of an additional "/ @type /" and the fact that the annotation is in a comment, not in code. That had the benefit that that all code for closure was valid JavaScript, which was key in the days before basically all production JavaScript went through a transpilation step.
>
It didn't support most module systems until this year.*ES6 modules maybe, but it's supported CommonJS and AMD modules since 2011[1] and its own module format before that.
The real reasons I think it didn't catch on are that it came out too early for much of the JS world, the closure library is written verbosely/awkwardly (though there's no reason to touch it when using the compiler, they're associated by name), and many thought you to annotate all existing code to use it instead of adding annotations incrementally.
[1] http://www.nonblocking.io/2011/12/experimental-support-for-c...
Here is an example type of a map function in TypeScript:
declare var map: <T, U>(f: (t:T) => U, t:T[]) => U[]
I cannot figure out the equivalent @type annotation in Closure using these docs: https://developers.google.com/closure/compiler/docs/js-for-c...
TypeScript didn't succeeded yet, but it is emerging with a great press coverage. It will be interesting to see people's preferences changing once they got a feeling how safe programming adds not only to the productivity, but also to longer term maintenance.
And in my opinion, the ecosystem doesn't matter that much. Otherwise Java should have won with its coverage of open source libraries.... or Perl should have won earlier... or... you get the point. It matters in the beginning, but not on the long run.
Parsing Javascript can also be a performance bottleneck for some applications as Javascript parsing is somewhat expensive in comparison with Webassembly.
The only thing that I don't understand is why TypeScript isn't just considered a required client (or Node) Best Practice at this point.
There are other languages that I prefer for specific domains, of course. But if you're writing code that needs to run on a web client and/or that needs to run in Node, TypeScript is the only way to go.
Maybe it's a little bit of fatigue setting in, but at this point, my next foray into a new language will be something properly compiled like Rust or Swift, not a transpiled language.
This is not to detract from Typescript or Purescript or anything else like it. There's some amazing work going on, but for now, I'd rather learn the ins and outs of javascript instead, warts and all.
I've never really cared for Coffeescript (because I felt like it brought very little at the cost of a very different syntax) but Typescript really improves my productivity.
It's also backed by JetBrains the IDE-maker.
I'm so sick of people spewing JetBrains' marketing points without checking the substance of it.
[1] Long story. "Trapped" programming Scala instead of Haskell by my own conservatism -- and now -- the need to support legacy systems. Still... it's way better than Java, so at least there's that. When thinking of Kotlin I always think of it as a sort of "what Java should have been", but when thinking of Scala I can't help but think "Well, it's not quite Haskell, is it?". (The poor type inference, the whole OOP thing, the lack of TCO means that any Monadic abstraction must be trampolined and that's just cruel.)
But yeah, it's absolutely my first choice for JVM or web work.
The complete lack of visibility for such things is what prevented me from adopting TypeScript. I couldn't get a clear answer which platforms supported async/await (there was a huge conversation on github which heavily implied, but never outright stated, that there was an ES5 target; yet the docs said it was ES6 only). A lot of the features have unspecified targets.
I wish their documentation were better.
But the thing that bothered me the most about JavaScript/Python was the fact that the tooling just doesn't have a clue, most of the time, what types things are. Misremember what has a member of what, exactly, or the spelling of a member, and you've got a bug.
TypeScript eliminates that kind of stupid bug and overall speeds up development by 2-3x. Yes, some of those bugs can be found in tests. But having to go back and fix them at all, tracking down exactly what the object structure is by hand (either in a debugger or digging through docs) versus "let the editor tell you exactly what members this class/object has, and what members its children have, so I can get it right the first time"?
And what about refactoring? TypeScript knows what everything in your code is. You decide to rename a member? Done! Just because there are twenty "init" methods, if you decide this particular call should become "init2", it will rename exactly the right members throughout your project.
Finally, the fact that it just has your back when assigning types prevents another entire class of bug.
No question; (optional!) strong types are a huge win, and as I said above, should be a required practice for any nontrivial app. You get the best of both worlds: Type safety without the manacles of having to specify everything.
Transpiling won't be obsolete until TypeScript is standard in browsers (where it could help improve JIT optimizations!), and probably not even then: We're looking at ES2017 before async/await is ready, which probably won't be in most browsers until 2018 at the earliest, and there will likely be more killer features on the horizon in the future that many people will want to use.
Where Babel shines vs. Typescript is that you get much more fine-grained control over which transformations to apply. Typescript doesn't seem to support just emitting async/await directly, which is what you would want if you target a browser which support async/await directly (Beta Chrome and Edge already support it behind a flag, and it's going to come to other browsers soon)
Seriously ? because it's not javascript and never will be.
The client side JS where I work was becoming a bit of a horrible beast so I started using TypeScript here and there when I worked on new things. It has really helped rein in some un-maintainable messes.
It's got to the point now where TypeScript is my default go-to language because it's so powerful.
Someone mentioned how great it is for strongly typing API's and libraries, and I have to second this. When there aren't typings available it forces me to RTFM instead of just prodding around in intellisense, so in some cases it actually helps me learn libraries better.
Just today I created a boilerplate project for webpack/typescript 2 [0]. It's not finished yet, but it's usable if you wanted to jump right into TypeScript with no run-time dependencies. As a bonus I modified the same boilerplate but for HTML [1]
[0]: https://github.com/deevus/webpack-typescript2-boilerplate
[1]: https://github.com/deevus/webpack-typescript2-html-boilerpla...
At one point in time, a 'this' bug ate up half of my day. Ever since moving to typescript, I haven't had a single 'this' bug make it past the compiler. I still don't fucking understand 'this'...all I know is that Typescript knows what it is and can tell me to fix something before I send it off to the browser.
Typescript will never be my favorite language...not even close. But since we can't actually get rid of javascript, I'm pretty happy we have typescript around to make it not suck so much.
function hypot(x:number, y:number) {
return Math.sqrt(this.x * this.x + this.y * this.y)
}
TypeScript does not warn about this case. (x, y) => Math.sqrt(x*x + y*y)
That can never have any state bugs, because it's a pure function (just like you can never have type errors with a sufficiently good type system).And you might be interested in the native JS function (since ES6) called Math.hypot. Happy hacking :-)
This is the best guide to "This".
Can you elaborate on your meaning? A language that requires transpiling by definition can't be more accessible than the language it transpiles into.
> At one point in time, a 'this' bug ate up half of my day. Ever since moving to typescript, I haven't had a single 'this' bug make it past the compiler. I still don't fucking understand 'this'.
'this' can be a little complicated but it's really not that bad. I like the dry way the MDN explains 'this' [1] if you find it helpful. Even if you're using TypeScript I still think it's important to understand (TypeScript does compile into JavaScript after-all; debugging the transpiled output without chrome maps can be necessary at times).
[1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
It's a funny definition of "accessible" that counts C as less accessible than assembler.
One thing though: the engineers started to write classes for everything. I had to catch that and forced them to stay as functional as possible. Does that happen to other teams, too?
And I really like to see WebAssembly to become part of our browsers and Typescript generating it instantly.
For example, if you have a lot of paginated lists you can write an abstract class that handles all the "get the results", "put them on a list", "display pagination", "on click display the next/previous page" trivia and then inherit from that to add the UI/presentation and any specific logic. It's absolutely possible in plain javascript but I shudder at the thought of writing something like that and even worse, refactor it. Typescript with OO and generics simplifies the task considerably.
As in everything in life: "dogma is bad", "παν μέτρον άριστον", "use the best tool for the job" etc. Words to live by.
For cross cutting concerns like pagination, we already have functions that enhance the pagination controls.
That said, Typescript is most likely to support WebAssembly when WebAssembly offers a GC implementation for it to use (the WebAssembly GC is planned in the medium to long term IIRC).
> surface TypeScript syntax
TypeScript syntax is... Javascript (ES 2015 or above) - plus the optional type annotations and some few minor additions like "enum" or decorators. Things like "interface" don't compile to actual code, they only serve the compile-time type checks.In our office it seems like the JS folks are sensing that they should "get on board" with the clear enthusiasm from the C# folks but there is resistance (mostly muttered quietly to each other to avoid looking like they don't get something that seems so obvious to others).
I remember trying out typescript with few tutorials, but so far mostly on the browser side (i.e angular 2 is in typescript) and when I poked around I couldn't really figure out how to hook up to the npm ecosystem.
Was that just a lack of decent google-fu that particular day?
Really, the main pieces that could seems a little mysterious are type definitions and compiler options. tsconfig.json exists in the root of the project for compiler options. Type definitions can be managed by a library called 'typings', or for TypeScript 2.0, type definitions can be managed with npm.
It's improved immensely though in the past months/year.
I would suggest this link: https://code.visualstudio.com/docs/runtimes/nodejs
I tried flow, but flow's comment syntax for type annotations is not compatible with JSDoc, and flow really needs a lot of work still. I am hopeful it will improve, but I feel presently it isn't ready for primetime for large codebases on the server side. (I guess it works great for React though).
Pretty new to TS but I like TS a lot as well!
Heljsberg himself (the creator of TypeScript) likes functional programming a lot and brings the best features to his languages.
I haven't tried TypeScript yet, but I look forward to it :)
http://www.itwriting.com/blog/2443-anders-hejlsberg-on-funct...
I see a lot if ts hype, but flow has been getting the job done for me. When non-nullable types come to ts via 2.0, I could see myself switching if there are viable reasons.
That, coupled with Flow being harder to get up and running, makes TypeScript much more popular for the average developers. I still prefer Flow though :(
The difference is having a compiler and a type system that tells you when you've broken things. Most people that have actually used TypeScript for any length of time understand the type system to be invaluable.