TypeScript vs JavaScript: Which to Choose for Your Next Project?
Clocking in at over 20 years old, JavaScript is one of the elder statesmen of the programming world. It’s also, according to the developer community HackerRank, 2023’s top five most popular programming language. This longevity, driven by continued demand for web apps, has put the spotlight on JavaScript’s inherent limitations.
Table Of Contents
- Dynamic and Static Language Types
- What Is TypeScript?
- What Problems Does TypeScript Solve for JavaScript?
- Do Large Distributed Teams Use TypeScript?
- The Difference Between TypeScript and JavaScript for Complex Development/Deployment
- The Problems with TypeScript
- Is TypeScript the Right Fit for You?
- Companies that Use TypeScript
- TypeScript or JavaScript?
Dynamic and Static Language Types
JavaScript has been adding more features to remedy its growing pains. They recently added new ways to import modules, new structures (like classes), and more utility methods. But none of these can address one fundamental problem: JavaScript is a dynamically typed language.
There are two language types: dynamic and static.
A language is said to be statically typed when you have to declare a variable as well as the type of elements it will contain. For example: if a variable stores a number, its type must be an integer, if a variable stores a word, its type must be a string. JavaScript, because it is dynamic, doesn’t let you do this.
But there is a solution. And it’s brought to us by Microsoft, who noticed the growing pains in the JavaScript ecosystem and decided to act.
What Is TypeScript?
TypeScript is a superset of the JavaScript language. Sorry, a what? OK, time for a bit of math theory. Set A is considered a superset of set B when all elements in B are contained within A. In layman’s terms, this means that TypeScript brings in features (interfaces, enums, types, and decorators) that JavaScript doesn’t natively support. What is great about this approach is that these new structures and features can be employed as if defining a standard JavaScript variable. So no need to change anything codewise!
What Problems Does TypeScript Solve for JavaScript?
As mentioned, JavaScript was conceived in a very different Internet age. The TypeScript ‘upgrade’ includes features that build on the strengths of JavaScript, and improves on its weaknesses. Let’s take a look at some of the highlights:
Syntactic Sugar
Syntactic sugar is a syntax style within a programming language that is designed to make things easier to read, or ‘sweeter’, for human use. TypeScript allows developers to satiate their sweet tooth (sorry) by writing their JavaScript code with additional syntactic sugar.
But how does this look exactly?
Example 1:
You can set types for variables, so you won’t have to spend time figuring out the type of the variable.
1let myVariable: number = 5;2
Example 2:
Imagine you have a function that receives a parameter. Before TypeScript, you couldn’t know what attributes an object had. But now, when specifying the type of a parameter to be MyParameter
, you can only use attributes as described in the interface.
1interface MyParameter {2 id: number;3 name: string;4 age: string;5}67function myFunction(param: MyParameter) {8 console.log(param.name)9 console.log(param.attr) // Throws an error because property 'attr' does not exist inside MyParameter10}11
Auto-Complete
Auto-complete is only as good as the suggestions it throws at you. And, because it’s not really possible to implement good auto-complete support without types, this is a welcome addition. It provides auto-complete scenarios with more accuracy for statement definitions, function calls, and object creation.
Static Type Checking
Static type checking, performed before the code is executed, is one of the most important features of TypeScript. With it, developers can detect errors faster (preventing those silly embarrassing typos someone else spots in QA).
Let me attempt to explain why with the following example:
1let myVariable = 5;2myVariable = "Changed to string";3myVariable = { };4myVariable.a = "myNewProperty"5
In JavaScript, this is ‘valid’ code. That’s because you can initially define a variable as an integer, then change it to a string, and finally to an object. This doesn’t make any logical sense, but it is possible. As a result of this, JavaScript developers regularly face type compatibility issues.
1function sum(a, b) {2 return a + b3}4
I can call the above function as follows:
1sum(1, 2)2sum(1, "3")3
The function will accept those values, even though I assume the parameters will be numbers. For the latter case, the answer will be ‘13’ instead of ‘4’, because it assumes it’s a string concatenation instead of a real sum. These incompatibilities are what make JavaScript a very unreliable programming language.
TypeScript comes with a syntax that allows you to write something like this:
1function sum(a: number, b:number) {2 return a + b3}4
So when you try to call the function with:
1sum(1, "3")2
It will show an error saying “Hey, I expected to receive an integer and you passed me a string. Fix this!” or perhaps something less conversational. That’s Static Type Checking, it’s also why TypeScript makes JavaScript a more reliable language.
It prevents, for example, the possibility of declaring a variable that stores a number and for some reason becomes a string during the execution of the program. In consequence, the code which is written has more consistency.
Do Large Distributed Teams Use TypeScript?
When a company has a distributed team working on the same code base, communication between members can be problematic. Unless the code can speak for itself.
While TypeScript code is often more verbose, its readability is improved. This is because, when you set types for your variables, you know exactly what to expect inside a function (as well as what value needs to be returned from a function and what type a variable can store). According to Sarah Mei, an Architect at Salesforce, “A type system can replace direct communication with other humans”.
This readability translates into performance and less technical debt. Oh, and you’ll avoid breaking someone else’s code!
The Difference Between TypeScript and JavaScript for Complex Development/Deployment
Writing unstructured JavasScript code can be a benefit and a vulnerability. It’s a benefit when building small apps – as they can be built faster – but a vulnerability as the app grows in complexity.
Let’s imagine you have a form on your website to collect new user information (name, age, email) this form triggers a welcome email that uses all those fields. Later, after your app codebase has become much larger, you decide to remove the ‘age’ field from the form, but you forget that the input from that field is used in the welcome email. In standard JS you will not be notified of this issue – the app will only fail during the execution. That’s because plain JavaScript doesn’t have that level of validation. TypeScript is different: whenever something is broken, you’ll be notified right away.
Runtime Compatibility
One of the most discussed characteristics of TypeScript is how it compiles code into plain JavaScript. Let’s dig a bit into how this works.
Each browser has its own JavaScript engine, and each engine interprets JavaScript slightly differently. To mitigate this problem, TypeScript lets you compile the code, and transform it into a version that is compatible with all browsers. The code is first written in a specific version of JavaScript. It is then transformed to a target output that will be the same code but written in another version. These versions are easily configurable via the tsconfig.json file (in which your source code is TypeScript code and the target is chosen by you). Normally, the version used as a target is called ES2015.
Because the whole development process starts and ends with plain old JavaScript code, it will run on any browser, host or operating system. This means the days of writing specific code for every browser version are behind us.
More Robust Software Development
JavaScript is classified as a multi-paradigm language. Paradigms are often used to classify programming languages based on their features (for example, the way its code is written and the structures used). A multi-paradigm language – like JavaScript – allows developers a number of ways to code any one solution. For example, using Object Oriented Programming or Functional Programming paradigms.
Quick sidebar: a lot of people prefer to use Functions rather than Classes. I’m not one of those people. The complexity of the keyword ‘this’ inside JavaScript makes people fearful about using Objects instead of Functions. The good news is that TypeScript can live in both worlds – just like JavaScript. If you don’t want to use Classes, then feel free to stick to Functions. That’s ok, you will still be able to write scalable code ;)
Despite JavaScript being classified as a multi-paradigm language, the lack of features like interfaces, decorators and enums prevented developers from using the entire power of the Object Oriented Programming paradigm. By adding these features, TypeScript enables developers to use better structures to access and represent data. Making the software development process way more robust.
Type Intersections
An intersection type effectively combines multiple types into one. This is powerful because you can now create an object using attributes that are defined inside multiple types. In other programming languages, like Java or C#, this would be like implementing multiple interfaces from a class.
In JavaScript, there’s a concept called mixin. A mixin can be defined as a class that contains methods used by other classes, where those methods are not located inside the parent class.
Let me step back to add some context. In Object Oriented Programming we define parent classes and children classes, also known as class inheritance. We use class inheritance in order to reuse code, but this code needs to be defined inside the actual class or inside its parent. The difference with mixins is that those classes won’t inherit the code from their parent classes.
Intersection types – by allowing us to manage methods or attributes from multiple interfaces into a single object – achieve the same result as if we used mixins. Let me demonstrate this with an example from the official documentation.
1function extend: First & Second {2 const result: Partial = {};3 for (const prop in first) {4 if (first.hasOwnProperty(prop)) {5 (result)[prop] = first[prop];6 }7 }8 for (const prop in second) {9 if (second.hasOwnProperty(prop)) {10 (result)[prop] = second[prop];11 }12 }13 return result;14
With this piece of code, I can merge two objects like this
1const newObject = extend(new Object1(), Object2.prototype);2
Another simple example:
1interface Runner {2 run: Function3}45interface Swimmer {6 swim: Function7}89type RunnerAndSwimmer = Runner & Swimmer; // Could be Runner & Swimmer & Dancer ....1011const person: RunnerAndSwimmer = {12 run: function() {13 console.log('I can run!')14 },15 swim: function () {16 console.log('I can swim!')17 }18};1920person.run(); // prints I can run21person.swim(); // prints I can swim22
In this case, I can create a type that combines two (or more) types, giving me the ability to define an object with multiple methods that come from different types.
NB: To use intersection types, use the ‘&’ character. Wield this new power with care!
Union Types
Union types are somewhat different from intersection types. To illustrate this. let’s create a function that takes a parameter. The kind of type (string, number, null, or a custom type like ’dog’ or ‘bird’) doesn’t matter, but you do need to set which one the function will receive.
For example:
1interface Dog {2 run: Function3}45interface Bird {6 fly: Function7}89function myFunction(animal: Dog | Bird) {10 if (animal.fly) {11 animal.fly();12 } else {13 animal.run();14 }15}1617const dog: Dog = {18 run: function () {19 alert("Let's run dogs");20 }21};2223const bird: Bird = {24 fly: function () {25 alert("Let's fly birds");26 }27};2829myFunction(dog); // prints Let's run dogs30myFunction(bird); // prints Let's fly birds31
In this case, it gives flexibility to the function to take a dynamic parameter, but with a limited scope.
NB: to use union types, use the ‘|’ character.
Great New Features at a Low Cost
I know that sounds like an infomercial, but in this case, it’s true. TypeScript won’t add any significant overhead to your application since all those additional features will disappear after being compiled. After all, the code executed in production is just plain ol’ JavaScript.
The only cost? Slightly larger JS files.
The Problems with TypeScript
This minor overhead to the code bundles leads us nicely to the downsides of TypeScript. And there are a few.
Dependency on a Third-Party Library
You might be skeptical about this whole external library setup. “How can a library be used more frequently than its native language?”. It’s a fair question, but there is a precedent here. Jquery is a library that makes it easy to manipulate elements on a web page. The buzz around this library resulted in the JavaScript community focusing on the library and not on the evolution of the language itself. People were learning JQuery but didn’t learn the root language. It’s a bit different here though because TypeScript is not a library that changes or isolates JavaScript, but one that adds capabilities to it.
It’s also important to note that every piece of JavaScript code is also valid TypeScript code, but not the way around. Additionally, the types are optional. The intention is not to replace JavaScript, but to add capabilities to it.
Is Learning TypeScript Harder than Learning JavaScript?
Yes, the learning curve is greater than just learning JavaScript. But if you consider what you get for that extra time investment, it’s a fair trade-off. Anybody with prior experience in plain JavaScript will be able to hit the ground running here.
Productivity With JavaScript vs TypeScript
Some people argue that using TypeScript can slow down productivity. That’s only true in a short-sighted sense. If you consider the reduction in technical debt from investing in the longer TypeScript view, I would argue that it increases productivity. This obviously depends on the complexity (and quality) of your work.
Additionally, the necessity of compiling the code to another JavaScript version may sound like a nuisance, but this step is often added to the continuous integration pipeline (so just before the code goes to production) and thus is typically automated.
Increased File Sizes
TypeScript files are larger than their JavaScript counterparts. How much larger depends on multiple variables. Research I found indicates that TypeScript files typically come in at 20% to 30% larger than JavaScript files. Though in my experience, the increase was less pronounced.
Is TypeScript the Right Fit for You?
All this leads us to the burning question. While I am (clearly) a proponent of TypeScript, is it the right tool for you? After all, as we’ve seen, it is not a silver bullet. There are some downsides.
It’s always worth weighing up the pros and cons of any technical decision in relation to your specific needs. For example, are the improvements worth the time required to change your process and train your team?
Getting Started with TypeScript
If your answer is a resounding “Yes!”, then let me send you on your way quickly. Holding your hand through learning TypeScript is beyond the scope of this article (I’m just trying to convince you should install it!).
TypeScript is a dependency. This means the first step is to include it on your project and configure your IDE (Integrated Development Environment) or text editor. To include it, you will need to use NPM or YARN, which are the default dependency managers for JavaScript.
Companies that Use TypeScript
According to Stackshare, 4792 companies use TypeScript in their tech stacks, including Slack, Asana, DoorDash, and Canva.
TypeScript can be configured within many modern web frameworks, and support is continually growing. The team behind Vue.js, for example, is rewriting their next major version to include TypeScript. So, while many frameworks have TypeScript support, they don’t all bake it in. Facebook’s React library defaults to its own type system: Flow.
But TypeScript not being the only tool in this genre is a good thing. It’s simple market theory: having multiple tools with the same end goal leads to a faster evolution of the ecosystem and avoids having a single voice dictating the path that will be taken.
Additionally, TypeScript is not limited to the client side: it can also run on the server side! Currently, this can be done with Node. But Ryan Dahl, the creator of Node, is developing Deno, which will also be capable of running TypeScript.
TypeScript or JavaScript?
TypeScript could be a look into the future of JavaScript. And if it is, I like it!
It can really improve the developer’s experience, allowing you to write code effectively and efficiently. Microsoft – and the huge community they have fostered – have done a great job at improving JavaScript where it needed it most. Now, go turbocharge your JavaScript!