Need advice about which tool to choose?Ask the StackShare community!
ES6 vs TypeScript: What are the differences?
Introduction:
ES6 (ECMAScript 2015) and TypeScript are both programming languages that are commonly used for web development. While they share similarities, there are also key differences between the two.
Strict Typing: One of the major differences between ES6 and TypeScript is the presence of strict typing in TypeScript. TypeScript enforces static typing, where variables and function parameters must have specified types. This helps catch potential errors during development and improves code reliability. On the other hand, ES6 does not have built-in support for strict typing and allows for more flexibility in variable types.
Object-Oriented Programming Features: TypeScript provides support for features like classes, interfaces, and modules, making it a more object-oriented programming (OOP) language. It allows for the creation of objects, inheritance, interfaces to define contracts, and modularization of code. ES6, however, has limited support for OOP features and focuses more on adding new features and syntax improvements to JavaScript.
Compilation: TypeScript is a superset of JavaScript, meaning that valid JavaScript code is also valid TypeScript code. However, TypeScript code needs to be compiled to JavaScript before it can be executed in a browser. This extra step of compilation is not required in ES6, as it can be directly executed by modern browsers that support ES6 features.
Tooling and IDE Support: TypeScript offers robust tooling and support from popular Integrated Development Environments (IDEs) like Visual Studio Code. It provides autocompletion, code navigation, and error checking, making development more efficient. While some ES6 features are supported by IDEs, they do not provide the same level of tooling and support as TypeScript.
Backward Compatibility: ES6 is designed to be compatible with older versions of JavaScript, allowing existing JavaScript code to run without modification. TypeScript, on the other hand, introduces additional syntax and features that may not be supported by older JavaScript runtimes. This can make it challenging to integrate TypeScript into projects that heavily rely on legacy JavaScript code.
Community and Adoption: JavaScript has been around for a long time and has a large and active community of developers. ES6 is widely supported by modern browsers and has been adopted by many developers across different industries. TypeScript, although gaining popularity, is still relatively newer and has a smaller community. It is often used in larger projects or organizations that require strong typing and better tooling.
In Summary, ES6 and TypeScript differ in their approach to typing, support for object-oriented programming features, compilation requirements, tooling and IDE support, backward compatibility, and community adoption.
I consider myself now (after a few years of practice) to be a decent JavaScript/Node.js practitioner. So can someone convince me that I have to learn TypeScript and use it in my everyday life? In other words, why would TypeScript be necessary over some proper ES6 compliant code with strict mode enabled? Any thoughts/opinions are welcome.
EDIT 07/20/2020 : Thank you all for your feedback. I'm definitely going to invest some time in some TypeScript education in the long run. Apart from all the points you made in your responses (static typing, compilation, codebase consistency, etc ...), the fact that Deno may go big (which I hope, the improvements over Node.js could be life changing) and that Visual Studio Code (which I use) is built on top of Electron using TypeScript is what convinces me.
I was asking myself this same question a few years ago. I felt that ES6 provided a terse, declarative syntax, that in combination with unit tests was reliable enough. Dynamic typing kept the code looking clean and left most functions generic and reusable for several data types. However, as your code base starts to grow and more and more "ad hoc" data types are introduced. It starts to become very hard to maintain and refactor code because you have to keep long call chains in your head and you sometimes don't know if you can remove a field from an object without introducing a runtime error. In essence, the less strict a programming language is the more you will have to test explicitly all the time. On top of that JavaScript is really good at coercing types in weird ways.
So the main benefit that TypeScript brings is static typing. You make your code more explicit, thereby limiting the number of unintentional behaviors that are possible. The compilers type checker can suddenly take care of testing these extra constraints for you and you start removing this burden from your unit tests. As a matter of fact TypeScript has a pretty advanced type system, a magnitude better than the current Java version (14) or Go-lang. One of these features are union types (aka. coproduct, sum type, etc). This lets you represent your types as "this thing" or "this other thing". Returning a disjoint union can make your code even more explicit and thus further limiting the number of unintentional behaviors. A simple example of this is the head
function that returns the first element of a list. Either you get the value or you get undefined if the list is empty. A better approach is to return a Maybe
type which is either an instance of Just(<value>)
or Nothing
. This tells you that the code calling head
needs to handle exactly two possible cases. Languages with even stronger type systems like Elm and Haskell can even enforce that your code won't compile unless you handle all the possible cases for any union type. So again the compiler helps you avoid more runtime errors.
So to conclude the benefits of using a language with strong static typing:
- Compiler helps you avoid runtime errors
- Substantially reduce number of explicit unit tests
- Better security and reliability by preventing unintentional behavior
- Let's you refactor code with confidence
- Code becomes more self-documenting
I've been feeling the same way and it was almost too simple for me. First, strongly typed languages are objectively better for catching errors during development instead of during production so a small amount of work upfront pays huge dividends later. But the easy part is how actionable it is.
Find a codebase that you want to convert. For me, it was a server that I wanted to convert to Firebase cloud functions to go serverless. I took my server.js file and copied it as server.ts. I created a simple tsconfig.json file in the root with some standard settings online and then I let the VS Code IntelliSense guide the migration. It was so much easier than I expected and I learned TypeScript as I was converting my codebase.
It was almost too easy and now I have all of the benefits of feature-rich and built-in assistance in my code-editor. Documentation on hover, clear and clean errors. This was only about 2 weeks ago and I am not sure I'd ever go back to Vanilla JS now. It was love at first use with me.
TypeScript is a superset of ECMAScript, so you can continue to code in your familiar ES6 code style and then slowly sprinkle in some types when you feel like it. No need to dedicate extra time to learn it. TypeScript gives you more options without taking any of the options you have in plain ES6 away.
typescript provides static typing
The benefits of Typescript are more pronounced for codebases that are large and require ongoing maintenance. Having said that, Typescript was recently voted #2 most loved language behind Rust. Learning it won’t feel like a chore. You’ll have fun, write more maintainable code, and probably look back and wish you’d done it sooner :)
I am a big advocate for TypeScript. It even became a job requirement for me. I would probably refuse to work on a JavaScript codebase again.
Just to add to the other pieces of advice:
1 - Compile-time errors
Typed languages give you compile-time errors on top of runtime errors. If your code compiles it means you already have cleared a few bugs before you even start running your app.
2 - Documentation
Having typed properly your code gives your documentation. You know what is the type that any variables hold, You know what is the return type of every function... With pure JavaScript, you often have to rely on naming conventions. With TypeScript, you can enter any codebase and straight away know the type of variables, the shape of objects, etc...
3 - Auto-completion
Types give you auto-completion. Using a third-party library or accessing properties of an object, your IDE, will give you all the possible options and will moan (compile-time error) if you try to access a property that is not defined or try to map over an object for example.
4 - Let you learn other languages more rapidly
As a JavaScript developer, it is often impossible to read a codebase of a different type-language (java, swift...) and understand. Understanding types will allow you to (more) rapidly understand other programming languages.
TypeScript is not perfect in my opinion as it is not part of the JavaScript language, and you often struggle in trying to stop Typescript "complaining". But the pros largely overweight the cons in my opinion.
One important thing in setting up TypeScript is making sure you enable strict rules. Such as "strictNullChecks", "noImplicitAny", "strictFunctionTypes". If you TypeScript configuration is too permissive, you might be ending up writing more code for not that much safety. Basically you want to catch as many errors as you can in compile-time and only run the app once you feel confident it should work.
Well, I am using Webstorm which has JSdoc support so I am getting type info in the IDE.
I don't need an extra layer of complexity and compilation in my code.
Type Inference can help in reducing TypeScript verbosity and make it look more like vanilla JavaScript. Directory Listing
From a StackShare community member: "We are looking to rewrite our outdated front-end with TypeScript. Right now we have a mix of CoffeeScript and vanilla JavaScript. I have read that adopting TypeScript can help enforce better code quality, and best practices. I also heard good things about Flow (JS). Which one would you recommend and why?"
I use TypeScript because:
- incredible developer tooling and community support
- actively developed and supported by Microsoft (yes, I like Microsoft) ;)
- easier to make sense of a TS codebase because the annotations provide so much more context than plain JS
- refactors become easier (VSCode has superb support for TS)
I've switched back and forth between TS and Flow and decided a year ago to abandon Flow completely in favor of TS. I don't want to bash Flow, however, my main grievances are very poor tooling (editor integration leaves much to be desired), a slower release cycle, and subpar docs and community support.
I use TypeScript because it isn't just about validating the types I'm expecting to receive though that is a huge part of it too. Flow (JS) seems to be a type system only. TypeScript also allows you to use the latest features of JavaScript while also providing the type checking. To be fair to Flow (JS), I have not used it, but likely wouldn't have due to the additional features I get from TypeScript.
We originally (in 2017) started rewriting our platform from JavaScript to Flow (JS) but found the library support for Flow was lacking. After switching gears to TypeScript we've never looked back. At this point we're finding that frontend and backend libraries are supporting TypeScript out of the box and where the support is missing that the commuity is typically got a solution in hand.
I use TypeScript because the tooling is more mature (the decision to discontinue TSLint in favor of moving all its checks to ESLint is a thoughtful and mature decision), there's a ton of examples and tutorials for it, and it just generally seems to be where the industry is headed. Flow (JS) is a fine tool, but it just hasn't seen the uptake that TS has, and as a result is lacking a lot of the nicer small things, like thorough Visual Studio Code integration, offered by TS.
We use Underscore because it's a reasonable library for providing all the reasonable helper functions missing from JavaScript ES5 (or that perform poorly if you use the default ES5 version).
Since we're migrating the codebase to TypeScript , we'll likely end up removing most usage of it and ultimately no longer needing it, but we've been very happy with the library.
We currently use TypeScript at work. Previously we used Flow (JS) but it was sometimes really difficult to make the types work the way you want. Especially non-trivial types were problematic. And the IDE support wasn't good, Flow took too much resources and sometimes remain stuck and do not show errors (I use Visual Studio Code). With TypeScript we almost do not have these problems. IDE support is superb, working with types is much easier and typing system seems more mature and powerful. There are some downsides (like partion inheritance etc.), but TS team is still pushing it forward. So for me TypeScript is clear winner.
I use TypeScript because it's adoption by many developers, it's supported by many companies, and it's growth. AngularJS, React, @ASP.NET Core. I started using it in .NET Core, then for a job. Later I added more Angular experience and wrote more React software. It makes your code easier to understand and read... which means it makes other people's code easier to understand and read.
I use TypeScript for Web Applications and for both frontend and backend because it has a lot of tooling around it and they really got the types and type safety right. Flow (JS) on the other hand lacks tooling and most of the times I scramble to find the right way of building my contracts in which TypeScript is very intuitive and natural. Additionally TypeScript is very similar to Java so your backend engineers and full stack engineers can work with it without much of context switch.
The only time I think Flow shines is (based on probably my outdated knowledge) Flow is/was the only option if you want/wanted to build a React Native application mainly because React Native transpiler at the time I was working with it would only work with flow.
I use TypeScript because I tried both on a Meteor project, and found the quantity of errors it enabled us to catch and the simplification of code it allowed was higher than Flow (JS).
I use TypeScript because it's the most mature/issue-free Javascript type-checker available, as far as I've seen.
I use TypeScript because of broad support, on tools, repos, community ... the only reason to consider flow is if you're a facebook employee
If you will start a project from scratch I recommend to use TypeScript. But, If you work with legacy projects written in JavaScript I recommend Flow (JS). Both tools have the same objective: reduce the bad code (which create illegible code, generate bugs e problems to maintenance). Flex helps you to avoid fall in bad codes, but TypeScript prevent you to c you to create bad codes. I believe cause this some JavaScript fans don't like TS, because TS block you to write some types o code. This is the fundamental difference between TS and Flow: Flow avoid problems, but no force. TS force you to prevent problems.
I use TypeScript because i love to program in Angular and used in node as well
I recommend TypeScript. When used correctly, TypeScript can enable your application to be scalable, easy to refactor, safe, and stable. One of the biggest draws of working with any typed language is that it forces you to think about your functions' inputs and outputs. This is invaluable as it can lead to more declarative, functional style code that ultimately can be easier to reason about.
TypeScript is however not a silver bullet. Just like anything new it takes time to fully understand the concepts of types, interfaces, abstract classes, and enums. In my experience engineers who excel when using TypeScript are those who have experience working with a statically typed language.
This post is a bit of an obvious one, as we have a web application, we obviously need to have HTML
and CSS
in our stack. Though specifically though, we can talk a bit about backward compatibility and the specific approaches we want to enforce in our codebase.
HTML
: Not much explanation here, you have to interact with HTML for a web app. We will stick to the latest standard: HTML 5
.
CSS
: Again if we want to style any of our components within he web, we have to use to style it. Though we will be taking advantage of JSS
in our code base and try to minimize the # of CSS stylesheets and include all our styling within the components themselves. This leaves the codebase much cleaner and makes it easier to find styles!
Babel
: We understand that not every browser is able to support the cool new features of the latest node/JS features (such as redue, filter, etc) seen in ES6
. We will make sure to have the correct Babel
configuration o make our application backward compatible.
Material UI (MUI)
: We need to make our user interface as intuitive and pretty as possible within his MVP, and the UI framework used by Google will provide us with exactly that. MUI provides pretty much all the UI components you would need and allows heavy customization as well. Its vast # of demos will allow us to add components quickly and not get too hung up on making UI components.
We will be using the latest version of create-react-app
which bundles most of the above along many necessary frameworks (e.g. Jest for testing) to get started quickly.
For our front-end, React is chosen because it is easy to develop with due to its reusable components and state functions, in addition to a lot of community support. Because React is popular, it would be easy to hire for it here at our company MusiCore. Our team also has experience with React already. React can be written with ES6 and ES6 has a lot of popularity and versatility when it comes to creating classes and efficient functions. Node.js will be used as a runtime environment to compile the code. Node.js also has many different types of open-source packages that can help automate some of the tasks we want to do for the application. CSS 3 will be used to style components and is the standard for that.
Optimize-js
I will not describe this tool a lot here, because it's already good done by author on github
I just want to mention that this tool wrap up all immediately-invoked functions or likely-to-be-invoked functions in parentheses what is do a great optimization a JavaScript
file for faster initial execution and parsing (based on my experience).
The performance of application where I've introduced optimize-js
improved on 20% in a common (tested in Chrome
and IE11
).
- Clarification on Readme to the optimize-js
- Some of Nolan thoughts on the virtues of compile-time optimizations can be found in "Parens and Performance" – counterpost
Is it maintaining now? - Unfortunately, no (but feel free to send PR)
As our codebase grew in size, we were looking for ways to improve code quality. We chose TypeScript over Flow due to its rapid industry adoption and overall tools support.
We noticed how different open-source projects were migrating from Flow to TypeScript. Most notably, it was Jest, even though Jest and Flow were both developed by Facebook. See this HN thread if you want to dive into an interesting discussion around this move.
Additionally, at the beginning of 2019, both Babel and ESLint enabled seamless TypeScript support, which allowed easy migration path in a backward-compatible way.
Initially making a decision to use Flow vs Typescript we decided to go with flow as we wanted our code to run in a way we wrote it, because when using Flow types are simply removed from the code without modifying the code itself. Sadly, the type system of Flow was in some cases very hard to understand and declare the types correctly, especially in cases when the structure is very dynamic (e.g. object keys and values are created dynamically). Another reason was bad integration with IDE and frequent crashes which made DX very poor. Therefore, we made another evaluation of Typescript and decided to move towards it. As our code base was pretty big when we decided to migrate to TS we couldn't just stop and re-write everything, that's why we started writing new modules in Typescript as well as transforming old components. To make that possible we had to configure Webpack loader to support simultaneous bundling of Flow&JS and Typescript. After around 2 months of the transformation we have around 40% of code being written in Typescript and we are more than happy with integration TS has with IDE, as well as ease of declaring types for dynamic modules and functions.
Pros of ES6
- ES6 code is shorter than traditional JS109
- Module System Standardized52
- Extremly compact2
- Destructuring Assignment2
Pros of TypeScript
- More intuitive and type safe javascript174
- Type safe106
- JavaScript superset80
- The best AltJS ever48
- Best AltJS for BackEnd27
- Powerful type system, including generics & JS features15
- Compile time errors11
- Nice and seamless hybrid of static and dynamic typing11
- Aligned with ES development for compatibility10
- Angular7
- Structural, rather than nominal, subtyping7
- Starts and ends with JavaScript5
- Garbage collection1
Sign up to add or upvote prosMake informed product decisions
Cons of ES6
- Create Node.js1
- Suffers from baggage1
Cons of TypeScript
- Code may look heavy and confusing5
- Hype4