Static vs. Dynamic languages
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.
Microsoft actually noticed this limitation of JavaScript and presented us with the solution: TypeScript.
What issues does TypeScript solve?
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.
MORE PRACTICAL FOR DISTRIBUTED TEAMS
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!
MORE SCALABLE CODE
Writing unstructured JavaScript 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.
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 different 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: First, second: Second): 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);
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.
So, as you can see, TypeScript’s features can really improve the developer experience, allowing you to write code more efficiently. Microsoft – and the huge community they have fostered – have done a great job at improving JavaScript where it needed it most.
Hopefully, you found this information helpful in determining whether it’s the right fit for you. You can take a look at the
long-form version of this information if you’re curious about learning more about the topic.