Porting 30K lines of code from Flow to TypeScript
davidgom.es
davidgom.es
Migrating 15K LoC from JS to TS.
The author of Vue.JS also migrated Vue completely to Typescript.
At first I had major apprehension because of how much Microsoft generally enforces things on developers.
It's well know that if you start using C# , your entire stack will generally be MS based...(SQL Server, Azure etc... )
But after I did the migration , I was blown away by how confident and how much flexibility I had when i was writing my code.
Even if I have been writing code with Java / C# for nearly a decade , nothing has come close to Typescript in terms of productivity,flexibility and confidence.
Having used Javascript since before Node.JS , I think the whole idea of having to "transpile" my code to something or to respect some "rules" define by a company with a reputation that wasn't really "all in open source" .
But after using Typescript on multiples projects , you just can't go back , it's incredible how well it's scale without enforcing anything on the developers.
Hopefully , one day bootcamps will include Typescript in their trainings to demonstrate how typings can solve maintainability issues...
And yeah, Azure is a booming business for them. VSCode has a bunch of first-party extensions that reduce friction for working on their platform.
Fine if you just need PaaS app + RDB though.
You will need time to get used to it. I even use AWS for a Windows instance.
Trying to work with other databases after using SQL Studio is incredibly frustrating
https://www.youtube.com/watch?v=Vhh_GeBPOhs
Granted, they weren't releasing much open source then, but it was all free to use, and the quality was far above open source alternatives (e.g. think the Visual Studio debugger vs. GDB wrappers).
I think they just naturally figured out that there's zero advantage to keeping developer tools closed source.
Microsoft might seem to be an "open source champion" now, but remember that it is a publicly traded corporation with a fiduciary responsibility to maximize profits for its shareholders and a history of anti-competitive, anti-consumer practices.
Right now they are being warm and fuzzy to regain the developer mind-share they have lost over the past couple decades to open-source software. If they get a large percentage of developers using their tools and services (looking at you GitHub) I would not trust that they will continue to be so warm and fuzzy.
Imagine if VSCode becomes the defacto code editor. Then they add seamless integration with GitHub, including value-added features which are not available from other providers like gitlab. Developers accept it because everyone uses GitHub anyway. Then they add features to GitHub to integrate seamlessly with Azure, and bug tickets related to GitHub plugins for interop with AWS start to take longer and longer to be resolved. Then maybe one day they change the terms of service, and it's no longer allowed to develop GitHub plugins which compete with Azure. Then they release an update to VSCode which uses deep learning for code completion. On Windows it uses a new DX12-powered subsystem which makes it fast and responsive, while on Mac and Linux it falls back to a single-threaded solution which makes the whole application feel laggy.
In a scenario like that, it would be in principal possible to fork VSCode and make a more platorm-agnostic version, but how realistic is it that an individual, or even a small team will be able to keep up with a large corporation which seeks to make such an effort less successful.
Open source software is great, but if Microsoft owns the governance of those projects, and the up-streams and down-streams, they still have a lot of power over them.
This is what happened with Java, Go and Javascript growing rapidly while .NET took a long time to get out of legacy/desktop phase, partly because the tooling was fantastic but isolated to their own Windows platform. They've learned their lesson and have realized there are better businesses by providing the compute and making it easy to use with free and plentiful tools.
https://en.wikipedia.org/wiki/Visual_J%2B%2B
Microsoft does the same thing over and over - "embrace" a technology, "extend" it by adding some extra stuff to it that happens to work best on Windows then "extinguish" the tech once people are locked in.
Also see: Internet Explorer or Kerberos or Office document interoperability or AIM (messenger) or half a dozen other things.
Same here.
Isn't this truly amazing?
Take a jangly language like JS, and add some typing for the compiler, which forces you to write cleaner code in addition to all the compiler advantages ... combined with some really cool features and bang a magical, pragmatic language.
Aside for some script things for which Python is still a blessing, I'd chose TS for everything else, at least to start.
It just has the right mix of flexibility and expressivity etc..
Though TS is an MS project, I suggest it really is quite different, it's 'open from the start' kind of thing, you can have a loot at TSC internals. The team seems to be fairly dynamic and responsive.
Typscript is my #1 favorite 'invention' of the last few years, I think it will be around for a while, and I hope to see many more JS API's 'properly documented' with the help of TS.
Most compilers, after type checking and semantic analyses, basically generate a control flow graph with basic blocks. Javascript doesn't have goto so it doesn't allow you to express those low-level things natively, which is why emscripten has to include a relooper component to turn them back into loops and conditionals.
If you want a good language to compile to, look at LLVM. It's a language designed to be compiled to, and it's mind-blowingly easy to compile to than either C or JavaScript.
Part of me would love for TS to build one out and add shims as part of the transpilation process, but it would go miles out of the scope of what TS is trying to do. And I love that (compared to Babel) TS has no plugins and relatively few options.
I wish lodashy functions, and a few other things (Time?), were just integrated into JS, in a thoughtful way ... as part of the standard lib. So they could all be done in native code in the engine.
These suggestions fall apart over time because they aren’t environment agnostic and lack objectivity. The subjectivity in question, “I want feature X”, usually doesn’t take alternate positions into consideration.
jQuery rise (but also underscore and others "low level libs) was interwined with the need of common functionalities, such as the DOM manipolation and the ajax calls. I still remember when all you could use was the .innerHTML property and the "new" DOM level 1 api [ https://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/ ]. jQuery selectors were so game-changing that the "new" DOM api were basically copied.
I understand how incredibly difficult is to find a good balance between an "anemic" stdlib (like the barely sufficient c stdlib) to the giant ones (like java has had), moreso that a bad/poorly secured function should still be mantained "forever" for backward compatibility.
Still I think that this movement should go forward to finally have some form of "batteries included"
Such a library would only cover features which would be useful in JavaScript in general, not things which are tied to the web platform. (A good heuristic: if something would make sense on a web browser but not in node or on embedded devices or robots, it probably isn't in scope.)
I say this all with recognition that lodash greatly predates TS, and the maintainers have done an absolutely wonderful job in keeping up with the overall ecosystem (ESM, typings files, etc). I can't even begin to comprehend the amount of work that has gone in to keeping lodash so modern.
That being said, I wish the interaction was slightly better, since a lot of people just immediately bring in Lodash to any JS project.
[0] https://www.typescriptlang.org/docs/handbook/release-notes/t...
For example, a function which takes a property path (in the form of an array of strings) and an object as parameters and returns the value at that path inside the object still needs overloads for every single tuple length.
type Key = string | number | symbol;
function get<T, K extends keyof T>(path: [K], obj: T): T[K];
function get<T, K1 extends keyof T, K2 extends keyof T[K1]>(path: [K1, K2], obj: T): T[K1][K2];
function get<T, K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2]>(path: [K1, K2, K3], obj: T): T[K1][K2][K3];
function get<T, K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2], K4 extends keyof T[K1][K2][K3]>(path: [K1, K2, K3, K4], obj: T): T[K1][K2][K3][K4];
function get(path: Key[], obj: any) {
if (path.length === 0) {
return obj;
}
const key = path[0] as Key;
const rest = path.slice(1) as [Key];
return get(rest, obj[key]);
}
interface Foo {
foo: {
bar: {
baz: {
val: number;
}
}
}
}
declare const foo: Foo;
const num = get(["foo", "bar", "baz", "val"], foo);
In this case, num is implicitly typed as number, but if the path would be longer, you'd need to add more overloads.And I say that as a Java guy myself. TS is much more dynamic and less abrasive, IMO.
This is true, but I think it's an Angular thing rather than a TS thing.
Typescript gets its huge strength from being able to bring a slider of type safety from pure js - Wild West crazy to strong null checked safety.
Having that pragmatic option of a slider is great for productivity.
Agreed. And when you compare how TS was designed to how other languages were designed, it makes a lot of sense why TS ended up being such a great language.
Unlike virtually every other language in existence, TS was not designed from the ground up. It was designed with a very specific goal in mind: to adhere to the standards that JS developers had already converged on. So when a JS developer said if (foo), TS was built to realize that was an implicit type check against null. When a JS developer said if (obj.type === “bar”), TS read that as a way to ensure obj was in fact a bar.
It’s unlikely that a language developer working from scratch would have come up with these odd idioms, let alone prioritized their inclusion into a new language. But in the case of TS, all these idioms came from millions of lines of working code.
I think that’s why TS feels so enjoyable and easy to work with nowadays, whereas even the best of other languages feel a little clunky at times. It was developed prioritizing making real actual code idioms people wanted to do work.
Is it safe to say that Microsoft has probably created/designed more programming languages than any other company? I can think of a dozen off the top of my head...
I really wish Python had a decent type system; hopefully the Mypy project takes a leaf from TypeScript's book.
Also, I've found that Go does for Python much of what TypeScript does for JavaScript. Of course, Go's APIs are different than Python's and its type system is less expressive than TypeScript so it's not a perfect analog, but Go also brings speed, parallelism, sane concurrency (Python's async is a hot mess by comparison), sane deployment, and great editor integrations, which are things I sorely miss when writing Python.
Mypy and TC and Flow and many other similar projects seem to stem from the academic work on gradual typing from nearly 20 years ago. What we're seeing now is "practical application" of that research, and while different projects have different budgets, it won't be surprising if they all converge in terms of features at some point. I'm not an expert, by any means, but we've already seen this happening many times with languages and software platforms. At least this time the point of convergence is based on comp-sci research and not on the marketing one.
Each method is independent unless the class is a Generic[T].
You can define a recursive type by quoting the nested reference.
You can define a JSON type with recursive types.
You can create stubs. Some are in typeshed.[1]
Mypy recently added protocols to simplify defining callable types.
Python has always been slow to add new syntax. I think that's a good thing overall.
No, that’s not sufficient, or at least it wasn’t. The problem wasn’t symbol resolution, but Mypy actually gave you a recursion error. At one time they were intending to fix it by implementing protocols which hadn’t landed last I checked.
> You can create stubs. Some are in typeshed.
You can, but not for magical libraries like SQLAlchemy.
> Python has always been slow to add new syntax. I think that's a good thing overall.
Probably, but it’s hindering their typing story. Typescript solves the problem by building a syntax that compiled to JS, but Python has some syntax support but lots of things are shoehorned in.
I'd be willing to say it's actually the "heart" of the new MS. Eliminating the incentive to selling OS licenses is doing marvels for them.
It so turns out that there is a great sweet spot in between the straight jacket typing of classic Java/C# and the loose "do way ever you like" approach in Python/JS.
I don't want use another language that doesn't have optional typing and structural typing. It combines the best of both ends of the spectrum.
Have you tried using type hints (https://www.python.org/dev/peps/pep-0484/) with mypy?
I can completely relate. To me the greatest thing is the tooling around it. Using tide[0] on even plain js codebase is just amazing.
I really wish ruby had a TypeRuby compiler (to regular ruby). I know about crystal, but I still want regular Ruby, just with a type checker at compile time, not runtime.
I've ported code from JS to Flow and could say the benefits are similar to those of porting from JS to TS.
The most relevant part in this article IMHO is the conclusion:
> things like a strong community and availability of type definitions are more important because weak type inference can be solved by "handholding" the type checker a bit more.
I think it's important to highlight that this may be true of his project but not necessarily yours or mine.
Flow's type inference provides a much deeper level of confidence than TS with far less effort, for example, typing only the public interface of a module is often enough to surface type mismatch errors several functions deep within the module. In TS, you'd have to type every function signature to get the same level of confidence.
What worries me about flow is reflected in the comment from the facebook engineer linked from the article: it seems the flow team is focusing heavily on facebook-scale performance at the expense of most every other aspect of the project. A while back, the existential operator was quietly deprecated in the name of perf, and lately some updates have been of questionable soundness, e.g.
https://flow.org/try/#0GYVwdgxgLglg9mABAdxFAFAQwFyIPIBGAVgKb... (compared to http://www.typescriptlang.org/play/#src=function%20wut(a%3A%... )
I don't disagree, but isn't this the point? That by typing every function you can reliably have confidence in parameter types and return value types, and if your program is able to throw a type error on build, then it should and alert the developer that they're not logically correct in their implementation.
export function formatTime(time: Date) {
return digitize(time.getHours()) + ':' + digitize(time.getMinutes());
}
function digitize(n) {
return ('0' + n.toStirng()).substring(-2);
}
Just a single type declaration is enough to let Flow catch the typo here. In TS, you'd also have to write the argument types for `digitize`. Importantly, if you wanted to explicitly add arg types for `digitize` w/ Flow, your editor can tell you what they are supposed to be. function foo(n) {
return n*2;
}
foo("bar");It was such a big jump, after 8 months of it now. I am so much more productive than I was before. It's just not funny.
If I did the same as you. Going from JS to TS, what kind of experience (from there on in) should I be looking at?
Also, code is much more manageable, and refactoring is tons easier.
With enough Babel plugins, you can get ESNext functionality that does whatever you want (some of those early stage proposals are really cool! They might go away tomorrow, but hey, so cool!), so Typescript's old advantage of offering more language features is kinda nullified.
In the end, I started writing the later part of my current project in Typescript, and I much more enjoy working on that part of the code than the earlier parts.
Stick to the 'basics' of TS, which are super general programming syntax structures and idioms - there's really nothing new you'll come across (maybe unions?) - so it's easy.
Then you can try some of the trickier things but frankly we don't use them that much.
You'll be up and running pretty quickly because you can mix your 'new' TS modules with old-school JS code no problem.
And then go from there.
I like TS because it's not some big new fancy paradigm shift: it's just typing, some other pragmatic things, and it works pretty well, very quickly.
It's the only tech I will actively evangelize as being 'the thing you need if you use JS' type thing.
No transpiration needed for node modules. No source maps, it’s same old plain JS that’s nicely checked by typescript.
TypeScript is, by far, my favorite type system. I love structural typing. I love conditional types (ReturnType<T>). I love things like `keyof T`. I love how good it's inference system is. I love how I can still use it in a JS file and still get type checking with JSDoc.
I tried out Dart over the holidays and it felt like a major step backwards. Seriously, hats off to the developers.
It's funny because I remember when Angular 2 was announced and that it would be written completely in TypeScript, they copped a lot of backlash for it, but it appears to have been a good move.
I exclusively have been writing in TypeScript for about 3 years now and it's crazy how good it actually is, especially for distributed teams in different time zones. The code is self-documenting and the number of silly mistakes being committed into our codebase has dramatically been reduced, combined with solid unit tests, we haven't really had a code level bug in what feels like months, browser bugs on the other hand...
My favourite thing about TS besides the types and interfaces is the compiler. I no longer have to use transpilers like Babel anymore because TypeScript handles compiling to many different module formats and targets. Back when I used Babel, it felt like pulling teeth because of the different plugins and packages you had to install and configure to use.
I find it really hard to use anything other than TypeScript now, it is simply too good.
That’s only because of Microsoft fanboys nowadays, .NET core is a pleasure to use on Linux and AWS with a variety of databases etc
In 2014, well before Microsoft's dotnetcore oss adventure, I ran the dev team at a startup. Our entire backend was C#. Our devs used the OS of their preference, and so we had Mac, Windows and Linux. Xamarin Studio is (was?) a remarkably decent IDE for something so niche.
We hosted it in Docker (bad call, it was way too new then) on Mono (great call, it Just Worked), on Linux. Data in Postgres. All of this was as easy as doing the same with eg JS or Java (and arguably easier than eg Ruby because C# has a proper cross platform dependency story).
There's nothing about C# that forces you to use SQL Server or Azure. Absolutely nothing.
It may be "well know" but it's entirely untrue.
Why the fuck...?
I love using Linux+PostgreSQL with F#, and deploying to AWS.
> Even if I have been writing code with Java / C# for nearly a decade , nothing has come close to Typescript in terms of productivity,flexibility and confidence.
Disagree. After doing JS & Java & C# & Perl & F# & TS (& a bit of others such as C, C++, Python), I think TS is just a giant patch to a language that is broken by design. And a patch is just a patch. Just fucking migrate to a decent language already! (e.g. F# or Rust)
This is very not true. For the past 2 years or so of using C# I never used MSSQL, Azure or even Windows.
Actually, this isn't true, and it's a fundamental property of TypeScript. It's actually the secret to being a TypeScript wizard, and the more you internalize it, the more questions about TypeScript you can answer in advance. I go through some others here: http://neugierig.org/software/blog/2016/04/typescript-types....
It's an important property in part for exactly the reasons this author worries about it -- it preserves the property always safe to type check and emit separately.
It's so fundamental to TS that their bug tracker, when reporting a bug, has a checkbox about whether your request violates this property, and if so they will discard your bug.
EDIT: This is incorrect ^, I misread your comment at first.
Thank you for bringing this up, this makes me feel even better about using Babel to emit code.
I vaguely recall there was some issue with the Babel emit of enums, but I can't remember it well enough to even remember whether it was fixed or not.
It's not its own language like Dart or the myriad of languages (Reason, PureScript, etc.) that transpiled to JavaScript. It's not just that its types are erased at runtime, as you point out; there are many nuances caused by the fact that it's a superset of JS.
While I think TypeScript is the best we have right now, I'm also a bit sad that we need to endure this kind of compromise. Maybe once Wasm because widely supported we can finally cast away the JS legacy and begin anew.
Their focus on soundness has shown the TypeScript team that they should give a lot more priority to getting the typesystem in a better shape over the years. If Flow didn't exist, I doubt we'd be seeing many of the features in TypeScript's --strict mode.
Plus, they were the first to develop some features like intersection types, or even some of the advanced type transformations. Shame it was (at least historically) a bit difficult to find them in the docs.
I'm hoping Flow can push TS to close up the remaining soundness gaps, and fix up some of their features (sealed vs open types is much better than the strange object literal checks in TS)
I really would hate for Facebook to kill off flow because Typescript is popular.
Microsoft, as great as they are at OSS, they still have to answer to a chain of Managers who are distant from the actual users of their software.
Just a few years ago, that would have been a laugh. Don’t get me wrong, I love the world we’re living in :)
To me, Flow feels like something they needed in Facebook and they happened to open source. Their main focus is still FB's internal use and the direction is set by it.
TypeScript, on the other hand, does not feel like this at all. They truly put the community first, or so I - and many others - feel like.
This is how most Facebook tools feel to me. It makes me afraid to use them. React is possibly an exception, but again -- too afraid to use it because Facebook's open-source offerings seemed to have only selfish goals in the past and often seem to be full of important bugs.
From an actual typing standpoint, I MUCH prefer Flow. The soundness guarantees were traditionally much nicer, and the inference it does made some things MUCH simpler (I was able to create a typedef for the react-redux connect function that made it so you could use an entirely un-typed `mapStateToProps` function, and it would infer the types from the reducers as the prop types automatically. It was amazing reducing the amount of code/types needed for each component, and it still gave us intellisense-style hover tips in our editors for what the actual types of each prop were.).
But at the same time, the tooling in the Flow world has always been MUCH worse. I found countless bugs on my own just with what I felt was pretty normal usage, there were many workarounds and issues on windows that were needed, flow-typed is an embarrassment compared to the @types org that typescript uses now, and there are so many weird options and settings that you can use in a `.flowconfig` file that are completely undocumented, deprecated but not documented somewhere, or are facebook-internal or meant to be used with metro (the react-native bundler) only or something.
I love flow, and I still greatly prefer the model they use over that of Typescripts in many ways, but at the end of the day Typescript is winning the tooling fight, and that tooling is bringing many people over. "Imperfect" types that work consistently are better than "perfect" types that are flakey or difficult to use because of the tooling.
It can be a real chore convincing Flow that working code works, and this can force you to use less-readable idioms to make the typechecker happy. It also lards up your code with extra dollar signs, angle brackets, and other crud, making it less readable.
These can be acceptable costs depending on your project, particularly the size of it (in lines of code, components, number of engineers, however you care to count).
Some people can’t seem to function without static (global?) types though, and this works for them.
Most of the HMR tools out there support Typescript in some way directly or indirectly (Typescript plugins for webpack, etc).
`tsc --watch` is quite handy and useful in those situations where an HMR tool doesn't support Typescript or you aren't using an HMR tool at all. (For instance, on one project recently I've been just using npm package `lite-server` which implements "BrowserSync" automatic reload and `tsc --watch`, because I currently don't need a full bundler like webpack, though I expect that to change soon.)
In v2 currently under way, you can use es modules which gives you a much better experience since you can reload a single file instead of an entire bundle (always sub 100ms update times).
[1] https://github.com/porsager/wright [2] http://porsager.com/wright/example.mov
I have a tool I developed that is a combination of a web server and web sockets that automatically rebuild and refresh the browser when a code file is saved.
Updates to both .ts and .css files trigger the build. The build step compiles the Typescript files into JavaScript and then merges certain JavaScript files together and makes minor modifications on the fly. I prefer to do testing in the browser as its easier for me to read the code output there, so once the code is properly packaged web sockets fires a notification to the browser to refresh the page which brings in the freshly built code.
My raw TS and CSS code exists in several different files for management, but the final packaged code provides the browser 1 CSS file and 2 JavaScript files, which decreases the HTML load time.
So yes, they (dynamically typed languages) have some advantages. Sometimes when I'm iterating quickly, especially on new projects, I don't want to fight with the compiler. BUT, I vastly prefer TypeScript to JavaScript because JS has a lot of foot-guns. I think when we get the existential operator, it will have less foot-guns, but I will probably never again write a new project for work in JS from scratch.
I really love the ideas Rich Hickey put forth in his most recent Clojure conj talk: https://www.youtube.com/watch?v=YR5WdGrpoug
The ability to spec out the shape of an object, and then in the different contexts in which you need some of that data, specify what you need, is an awesome solution to optionality (Watch the talk!). I absolutely love how much thought RH has put into the design of Clojure, and I think the final release of spec will be a close to perfect balance of dynamism and opt-in safety.
Of course, TS is a superset of JS, so adopting it little by little sorta gets me that balance I want.
The only time you're ever fighting the compiler in a modern statically typed languages with type inference is when you've made a mistake.
IMO, one of the geeat things about TS is that you can opt out of the type system for specific functions if you really want to.
You realise you can do the same thing in TS with its structural type system?
Static typing is nice when the tools given actually let you build nice APIs
I used to be excited about it but after a while of using it I see it more like a tool to migrate existing JS code or to interface with existing libraries written in JS, and not like an ideal tool to write code from scratch.
The reason is, the type system is actually incredibly complicated (to accommodate to all sorts of silly and messy things you can actually do in JavaScript).
I'd prefer using a more principled language for brand new projects. Which language is that? I'm not sure yet, but dynamic vs typed doesn't seem as important to me. I think ClojureScript is a better language than TS. Kotlin/JS also looks good, for a less "alien" language that is still better typed than JS/TS. But I don't have experience working on medium/big projects with these yet.
OTOH, for browser apps, the main plus for TypeScript is that if you pick a subset, ala C++, you get an OK language that never gets too far away from what you actually get when you convert the app to JS, so easier to debug and sometimes reason about.
So there you have it... I'm torn :-)
Can you give some examples?
I have a feeling if you need that, you are writing some complicated magic code, but I might be wrong.
`immer` is an immutable update library based on ES6 proxies. In addition to safely applying "mutative" code immutably, it also freezes the output to keep you from accidentally mutating it elsewhere.
An Immer maintainer just added some kind of a `DeepReadOnly` tag to its typings in a patch release, which broke things for a bunch of people:
https://github.com/mweststrate/immer/issues/289
This specifically broke our PR to convert `redux-starter-kit` to TS, with this lovely error message:
https://github.com/reduxjs/redux-starter-kit/pull/73#issueco...
I'm not saying every use of TS is that complex, but I do absolutely think that TS types can get ridiculously complex (and that people can get sucked into spending _way_ too much time trying to model dynamic JS behavior in static types).
The problem is, as soon as you provide those features, people will want to use them to add "type safety" to code that could otherwise be very simple. Sometimes simplicity is a better approach. This is why I say you will probably want to pick a subset of TS and leave the advanced types for interacting with legacy code or 3rd party libraries.
Also, I'll leave this link here :-) [2]
1: https://www.typescriptlang.org/docs/handbook/release-notes/t...
function f(leaves: Array<Leaf>, aggregators: Array<Aggregator>): Array<MemsqlNode> {
// The next line errors because you cannot concat aggregators to leaves.
return leaves.concat(aggregators);
}
That's just wrong, of course you can't concat aggregators and leaves! and Typescript is OK to not accept it. If you want that to be ok, you could do something like [].concat(leaves, aggregators) [...leaves, ...aggregators]Or as others point out, array spread does widen unlike concat (because it isn't an in-place operation).
https://news.ycombinator.com/item?id=18907771
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
Doing [].concat(Array<A>, Array<B>) is fine, because you did not specify the type of the array for the literal [], it's not a trick, in that case the type should be Array<any>, but it's casted to Array<MemsqlNode>.
/**
* Combines two or more arrays.
* @param items Additional items to add to the end of array1.
*/
concat(...items: ConcatArray<T>[]): T[];
/**
* Combines two or more arrays.
* @param items Additional items to add to the end of array1.
*/
concat(...items: (T | ConcatArray<T>)[]): T[];Flow recognizes that concat returns a new array, so it specifies that calling concat on an Array<T> with an Array<S> as an argument returns an Array<T|S>. Their actual definition is:
declare class $ReadOnlyArray<+T> {
// concat creates a new array
concat<S, Item: $ReadOnlyArray<S> | S>(...items: Array<Item>): Array<T | S>;
Personally, I'm ok with that and think it is useful. Although the return value could be an array of any type more general than T|S and the types of the argument arrays could vary. (i.e. Array<T>.concat(Array<S1>,Array<S2>,...): Array<? extends (T|S1|S2)>) but I don't know if that can be expressed in flow.I don't think either gets it perfect, but flow is trying to at least capture the fact that the return value can't be an array of a type that is disjoint from T|S.
In practice, I've been impressed by the level of detail of information that is captured and propagated by flow's type checker.
[0]: http://www.typescriptlang.org/play/#src=type%20NodeType%20%3...
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat> We converted a codebase that was adapted to Flow to TypeScript. This means that we obviously only found things that Flow can express but TypeScript can't. If the port had been the other way around, I'm sure we would have found things that TypeScript can infer/express better than Flow.
So he's aware of the conundrum, and, I hope, his readers too.
Consider the same functionality exposed as a function, it would seem be fine to type this as:
function concat(a: Array<A>, b: Array<B>): Array<A | B> { }Other than that aspect (which is very important!) I do think TypeScript is likely a better choice if you use any third party libraries that already have definitions available.
There is a much better typescript playground[0] that supports all options in the permalink, for example see this link[1] that has `removeComments` enabled.
[0]: https://typescript-play.js.org
[1]: https://typescript-play.js.org/?removeComments=true#code/PTA...
Actually, I’ve moved away from OOP in general in my JavaScript, only as a last resort. (Not going to put in long comment from tablet screen...)
That said, there is a Stage 1 TC39 proposal for partial application. https://github.com/tc39/proposal-partial-application
I have been using Ramda’s R.partial() function a bit, as well as some in-house stuff (e.g. - to generate 0-arity event handlers), but this would be a very helpful feature, particularly once IDE recognition becomes widespread.
Background: suite of related projects started in early 2015, ES5 on IE11 kind of limitations... (recently started using a transpiler for syntactic sugar)
const foo = (a: number, b: number): number => { /*...*/ }
to const foo = (a: number) => (b: number): number => { /*...*/ }And what I love the most: anywhere that I absolutely positively don't want to deal with it yet: `any`
This is one of my favorite aspects of TypeScript, the first-class support it receives in Monaco Editor (part of VS Code) which is one of the reasons I also chose first-class TypeScript support when making Autumn, since I could embed Monaco right into it and get countless amazing IDE features for free.
> unfortunately, we had to change a very small amount of runtime code to fix some logic that TypeScript could not understand
Would be very curious what this is, I've only found maybe one or two things TypeScript could not understand, and they were already under active development in the Github repo.
Is this just from LSP? Or are there extras that are built into VSCode?
VS Code is written in typescript though and the projects have a pretty nice cadence of new features. Typescript is very much a first class citizen in VS Code
(That, by the way, is one reason why you can trust that it's not going away anytime soon.)
We've just started a new Node project where typing was one of the main drivers and went through a similar thought process. We use Flow on our client code but the positive chatter about TypeScript had made us wonder if we should re-think that. We have similar thoughts on a lot of the trade-offs. Flow feels better at inference but the TypeScript ecosystem is amazing.
We ended up sticking with Flow for consistency (and we don't want to migrate the client right now). It's good to know that a migration isn't impossible if we ever change our minds.
We aren't planning on switching anytime soon because we also are using Relay which generates flow types for our GraphQL queries - but its good to know its doable if we need to.
[1]: https://github.com/facebook/relay/pull/2293
[2]: https://github.com/relay-tools/relay-compiler-language-types...
https://github.com/TypeStrong/ts-node
Article mentions ts-jest; can also recommend. I use Jest for all my TS projects from serverless to selenium. Its watch mode is fantastic.
I also typically use ts-loader with Webpack instead of Babel.
Eh, might as well toss a few more recommendations in there:
* source-map-support
* Bluebird for long stack traces with async/await(v8 now has a zero-cost feature behind a flag now though as of end of 2018)
* Get the debugger hooked up to your browser/nodejs process for a great debug experience
There's also ts-node-dev which is a variation of node-dev that auto reloads files loaded on change.
As for a bundler, parcel supports TypeScript out of the box which just allows you to write browser side code with TS without effort.
Typescript actually does support .js files. You just need to use the `--alowJs` option.
I've seen a few proposals around but it seemed that they were are stalled.
My hope is that since then we have examples like Python's PEP 3107 [0] that help make sense as where a TC39 proposal could move forward: encourage browsers to AST parse type annotations, and ignore them by default; leaving the actual semantics still to tools like Flow and Typescript until there is a better convergence in semantics and/or browsers have greater needs of specific type annotations.
I actually think we'll see more advances in webassembly first, though. It won't surprise me if Java makes a comeback for the frontend.
I get that TS may be a good idea if you deal with teams of mediocre devs to prevent they do stupid things but by talking with a couple of JS devs and looking at my own JS experience it seems like the desire of using TS vanishes if you reach a certain experience ans confidence using vanilla JS. It looks like the most people who embrace TS see JS as some kind of inferior thing, anyways - but that might just be a wrong observation by me.
Perhaps spending some time looking at how certain libraries write their type definitions will help you learn how to use them, if you're constantly fighting you are probably missing some fundamental concept that TS operates with. TS has also gotten much better at expressing more complex types over time and there are still more things on the roadmap.
For me TS only grows more useful as the size of the codebase increases. It allows safe refactorings you could only dream of in a large JS codebase.
Would you, perchance, be able to share an example of such an error? We generally strive to improve error clarity where possible~
> I found out that using JSdoc comments and relying on the linting abilities of my IDE
Ah. Well, spoiler alert: if your IDE is vscode or VS that JSDoc is actually still getting typechecked by TypeScript ;)
I don't consider myself a mediocre dev but I can still do stupid things and TS tells me before I run it.
> It looks like the most people who embrace TS see JS as some kind of inferior thing
JS does feel inferior once you use TS.
You sound like you're just used to your workflow if you had to pull hairs out by just using TS.
In my experience Javascript code bases end up being "add new code only", because changing anything is just too dangerous, because type errors are so hard to find. So after a while of several people working on the code base it just becomes a bloated spaghetti mess that cannot be untangled, because refactoring is nigh impossible.
But the problem is still that you cannot make any such change to existing large Javascript codebase, because you don't have the kind of tools that you need in order to do so with any confidence that you won't have an enormous amount of uncaught runtime errors when you're done. This is what a static type system gives you.
apart from the generalization i tend to agree
from uncle bob's article [1]:
> My own prediction is that TDD is the deciding factor. You don’t need static type checking if you have 100% unit test coverage. And, as we have repeatedly seen, unit test coverage close to 100% can, and is, being achieved. What’s more, the benefits of that achievement are enormous.
I've worked on high mantainable big JS projects (+40 devs) with 80%-90% test coverage. plus we were using GraphQL so inputs were valid types somehow.
if I start a new project today I would use only these technics (valid inputs + integration test) with no typed lang.
[1] http://blog.cleancoder.com/uncle-bob/2016/05/01/TypeWars.htm...
Seems like you'd have an easier time explaining what it does if you'd just called it "assert()" in the first place. This isn't a new concept, why does it have a new name?
You can certainly get substantially similar behavior just using asserts at the beginning of the function body and ensuring asserts at the end before a return are hit by all code paths (e.g. make an anonymous function that contains the body, then call it wrapped in a try/catch and assert on the return value.
Unless I'm missing something about design by contract, it's essentially just asserts at the beginning and end of a function.
Postcondition: guarantees that a method makes. For instance, it won't return null.
Invariants (incorrectly used): conditions that always hold true on a type, e.g. the starting index on a slice must always be greater or equal to zero.
https://en.m.wikipedia.org/wiki/Design_by_contract
I guess D is guessing via implications, but from what you've said it can't support invariants, meaning it doesn't strictly qualify as DbC.
With asserts, it's not uncommon to provide a separate switch, that defaults to excluding them in release/optimized builds, but you can override. And some languages make the distinction explicit in asserts themselves - e.g. in C# (and any other .NET language that uses the stdlib for this), Debug.Assert will be excluded #if DEBUG, but Trace.Assert will not.
type Maybe<T> = T | undefined;
x === undefined
Or:
type Maybe<T> = T | void;
x === void; // or: void?(x)
It's 100% fair to point to all of the things it doesn't provide, or indeed the way that it tries to make JS out to be some classical OOP language which it's not, but it's helped me track bugs and refactor code in ways which would never have been possible without it, and for that I'm grateful. In comparison to other tools such as mypy, TypeScript is light-years ahead in its general ease of use and community support.
It's a pretty sizable app. The migration wet pretty smooth and I would absolutely never go back. Typescript is amazing.
Errors that a compiler would normally save me from when doing Java/Kotlin are a major PITA when you are dealing with a foreign code base in Javascript. Over the past few weeks I've slowly gotten comfortable with the code base, the build system (rollup, babel, less, and a few other things etc.), and the frameworks we use (redom, mainly). After updating everything to their latest versions (e.g. babel 6 -> babel 7) and getting that working; I figured adding typescript should be straightforward.
Turns out this is super easy and delivers instant value. The hardest part was figuring out what part of our somewhat convoluted build.js script to modify so that it processes ts files as well. After finding the relevant for loop and adding the rollup plugin for typescript that seemed to be working out of the box. I added a tsconfig.json file to support some ecmascript2017 stuff we apparently are using.
After that it got easier. I fixed a few hundred lines of javascript code to have types. That's in my first hour of using typescript. VS Code and tslint are very helpful. I also found and fixed the first type bug that slipped through earlier: instant value.
Kudos to MS. Vs Studio Code is a game changer. I've been shying away from doingb frontend stuff for years for reasons of it seeming to be backwards to be coding blindfolded with your hands behind your back. VS Studio Code changes that. Autocomplete, quick fixes, refactorings, import organizing, etc. So much better than my browser telling me I messed up by not loading the page.
I renamed several js files. Worked my way through the clearly marked warnings. Mostly quick fix works reasonably well. You do need to replace the any type with something more appropriate usually (like e.g. string). Anyway, free of warnings and vs studio code also found and added a redom type definition for us. Awesome. Very impressed with how easy that went.
Typescript only for me going forward. Opting out of a perfectly good type system seems silly.
This shouldn't really have been an issue. It's always possible to not do any transpilation and leave it to another tool
Neither is perfect at displaying errors but that might also have something to do with your ts config. I also think that Webstorm is a much better editor than VSCode in every other respect, but for me VSCode is 1% better for my productivity so I am forced to use it.
This isn't (can't be?) true. Both editors use the same language server. I've used both and found their language support to be identical, and WebStorm feels a little more natural to me when using automated refactoring.
I also have both eslint and tslint set up through WebStorm, so I have everything integrated in one place: hinting, linting, compiler warnings, and compiler errors.
VS Code can do the same, as far as I know. I just prefer WebStorm for other reasons.
https://twitter.com/FraSteiner/status/1085479110774804480?s=...
If you enjoy being a human type checker, no-one in stopping you.
Type systems provide a lot of safety with less work, meaning less bugs and more productivity. Just having the definitions available when writing makes you go faster.
I hear this argument all the time. As well as the opposite: type systems slow you down and only catch easy-to-find bugs. Would love to see a real study that quantifies productivity among static and dynamic systems and ends this flame-war once and for all.