What is TypeScript and Why You Should Use it



Clocking in at over 20 years old, JavaScript is one of the elder statesmen of the programming world. It’s also, according to developer community HackerRank, 2018’s most popular programming language. This longevity, driven by continued demand for web apps, has put the spotlight on JavaScript’s inherent limitations.


TypeScript vs 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 the 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?


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.


let myVariable: number = 5;


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.



interface MyParameter {
id: number;
name: string;
age: string;
}

function myFunction(param: MyParameter) {
console.log(param.name)
console.log(param.attr) // Throws an error because property 'attr' does not exist inside MyParameter
}

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


“The static type checking feature alone will increase your productivity and reduce technical debt.”


Let me attempt to explain why with the following example:



let myVariable = 5;
myVariable = "Changed to string";
myVariable = { };
myVariable.a = "myNewProperty"

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.



function sum(a, b) {
return a + b
}

I can call the above function as follows:



sum(1, 2)
sum(1, "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 makes JavaScript a very unreliable programming language.


TypeScript comes in with a syntax that allows you to write something like this



function sum(a: number, b:number) {
return a + b
}

So when you try to call the function with:



sum(1, "3")

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 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 versions are behind us. Woop!


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



function extend: First & Second {
const result: Partial = {};
for (const prop in first) {
if (first.hasOwnProperty(prop)) {
(result)[prop] = first[prop];
}
}
for (const prop in second) {
if (second.hasOwnProperty(prop)) {
(result)[prop] = second[prop];
}
}
return result;
}

With this piece of code, I can merge two objects like this



const newObject = extend(new Object1(), Object2.prototype);

Another simple example:



interface Runner {
run: Function
}

interface Swimmer {
swim: Function
}

type RunnerAndSwimmer = Runner & Swimmer; // Could be Runner & Swimmer & Dancer ....

const person: RunnerAndSwimmer = {
run: function() {
console.log('I can run!')
},
swim: function () {
console.log('I can swim!')
}
};

person.run(); // prints I can run
person.swim(); // prints I can swim

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:



interface Dog {
run: Function
}

interface Bird {
fly: Function
}

function myFunction(animal: Dog | Bird) {
if (animal.fly) {
animal.fly();
} else {
animal.run();
}
}

const dog: Dog = {
run: function () {
alert("Let's run dogs");
}
};

const bird: Bird = {
fly: function () {
alert("Let's fly birds");
}
};

myFunction(dog); // prints Let's run dogs
myFunction(bird); // prints Let's fly birds

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 being 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 into 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 the 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 up 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. Which 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


TypeScript can be configured within many modern web frameworks, and support is continually growing. The team behind Vue.js, for example, are 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 their 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.


Conclusion


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!


Are you searching for your next programming challenge?
Scalable Path is always on the lookout for top-notch talent. Apply today and start working with great clients from around the world!


Post a Comment (0)
Previous Post Next Post