Why you should only use TypeScript ☝️

JavaScript is dead, long live TypeScript! I explain how TypeScript actively supports you in writing better and more reliable code in this article πŸŽ‰

Why you should only use TypeScript ☝️
Photo by Nangialai Stoman / Unsplash / Image / Image

JavaScript is probably familiar to anyone who has worked in web development. Everyone will also know the pain that JavaScript causes and many more will know the problems of JavaScript. In this article, I would like to show you what problems JavaScript has, which of them are the biggest and how TypeScript can help you.

The dilemma from the beginning πŸŽ‚

JavaScript has been around for umpteen years, since 1995 to be exact (wow, I was 8 years old then 😐). At that time, people were looking for ways to make websites more dynamic. In the beginning, there were hardly any standards and every browser manufacturer cooked their own soup. Older developers will probably still remember the clash between Netscape and Internet Explorer. But JavaScript continued to develop and became more and more popular and extensive. However, the exact history is very well documented at Wikipedia. It is actually quite interesting and also shows why many people confuse Java and JavaScript or why it is called JavaScript.

JavaScript - Wikipedia

The fundamental problem of JavaScript πŸ—οΈ

Now, however, JavaScript has a fundamental "problem". The code is not compiled in advance, as is the case with other programming languages, for example, but only when it is executed (just-in-time compilation).

Other languages can tell you in advance where there may be problems in your code. This is not possible with JavaScript (if you assume the normal standard). This is simply because JavaScript used to be written in simple text editors and there was little to no usable IDE for it. I can still remember very well how we spent nights working on websites in Notepad and simply couldn't find problems that were actually obvious.

This preliminary check is still missing in JavaScript today and this is exactly where TypeScript comes into play.

How exactly can TypeScript help me? πŸ†˜

Well, that's quite simple. In JavaScript, for example, a variable was not bound to a data type. You could just put anything in there, no problem. The following code is simply intended to demonstrate what is possible with JavaScript and why it is problematic.

var x = 1;

if (x === 1) {
  var x = 2;

  console.log(x);
  // Expected output: 2
}

console.log(x);
// Expected output: 2

So far so good. It works for now. But now user input or external data comes into play, then it may be that x is no longer numeric, but perhaps null or even an array.

var x = [1,2,3,4,5]; // not a number anymore

if (x === 1) {
  var x = 2;

  console.log(x);
  // Expected output: 2
}

console.log(x);
// Expected output: 2

In this case, the above code would not even truncate and exit, but it would check: (x === 1). As a array but not 1, it would simply continue without the instructions in the if. Even worse would be the code:

// Working code
var str = "Text";

console.log(str.replace("x", "s")) // Expected output: "Test"

// fatal failing code
var str = 1;

console.log(str.replace("x", "s")); // Expected output: Total descruction

The result would be that the JavaScript would throw an unhandled exception and simply refuse further execution. The bad thing about this is that it not only happens to you at development time, but also to every user who uses your application. In case of doubt, they won't even see what exactly the problem is, which makes debugging really difficult.

What exactly is the problem? πŸ€”

The problem is that you cannot ensure in JavaScript (except by checking at runtime, which in turn would produce more code that you have to maintain and which could potentially cause errors) that variables, parameters of methods, etc. can only accept certain data types. Keyword: typing.

This is exactly where TypeScript comes in (fundamentally) and tries to solve this problem by basing a typing on JavaScript.

TypeScript to the rescue πŸ›Ÿ

TypeScript was created by Microsoft ca. Microsoft in 2012 to help JavaScript developers write reliable and efficient code and is based on other languages that have similar concepts (C# as an example).

It is important to note, however, that TypeScript is not a programming language in its own right. TypeScript is merely a superset of JavaScript. This essentially means that all JavaScript code is also valid TypeScript code, but not vice versa.

This has the advantage that existing code or libraries can be (partially) migrated quite painlessly without (at least in theory) affecting the general functionality. TypeScript offers many concepts that are familiar from other higher-level languages. These include, for example, typing, generic types, interfaces, type inference and general signatures of classes, variables, methods, etc.

In this article, however, we will only focus on the aspect of typing.

To compile or not to compile 🎭

TypeScript code is not compiled in the classic way, but transpiled. This means that valid JavaScript that browsers can understand is generated from our TypeScript when the application is created. Browsers are not capable of native TypeScript. You can see this from the file extensions. TypeScript files are generated with .ts and then transpiled to .js.

Ergo: TypeScript only exists at development time.

Typing, what the hell? 😈

It's important. Very important. I myself have been programming JavaScript for years and didn't understand the point of typing JavaScript all of a sudden. But the advantages are obvious, which I would like to demonstrate to you with the following code. If we take the JavaScript code from above and put it into a TypeScript project, you can see quite quickly that the code is 1:1 compatible:

But the problem is still the same. But now comes the trick. We now say that x can only ever be numeric. We can do this with let x: number = 1;.

⚠️
If you use TypeScript, you should remove var from your vocabulary. Var is evil because it does not specify whether the variable may be written to multiple times (let) or whether it is a constant ( const).

If we now assign an array to x, we see something pretty cool:

Our development environment tells us that something is wrong here and we need to look here. Also, building/transpiling the application would abort here.

We would have the same behavior with our second code.

It would also directly complain about the double declaration of var str:

Which is completely correct. In JavaScript, however, this worked and repeatedly led to problems.

nuclear explosion GIF

This way, you can already see during development that you may have problems in the code before your application goes to the user. This gives you security, confidence that your application is fundamentally working and you can be sure that runtime errors are greatly minimized.

What else can/should you type? 🀩

But you can not only add signatures to variables, you can also create classes, methods and even your own interfaces to ensure that the data comes in the way you expect it to.

// Method signature
function add(left: number, right: number): number {
	return left + right;
}

// Classes
class Person {
    private name: string;
    private age: number;
    private salary: number;

    constructor(name: string, age: number, salary: number) {
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    toString(): string {
        return `${this.name} (${this.age}) (${this.salary})`; // As of version 1.4
    }
}

You can also use it to mix types (union types) and thus compose different types:

function successor(n: number | bigint): number | bigint {
    return ++n
}

The code would now expect the types number or bigint for n and return these as well. If there are problems, you will also see it.

What you absolutely shouldn't do! πŸ˜–

TypeScript offers different types for many different things.

Documentation - Everyday Types
The language primitives.

The guy, that you should forget right away is any. Any is practically the TypeScript equivalent of no typing. You are only telling TypeScript that this type can also be anything and you have the same problems as in JavaScript, but in TypeScript. This is exactly what the TypeScript documentation says:

You usually want to avoid this, though, because any isn't type-checked. Use the compiler flag noImplicitAny to flag any implicit any as an error.

In principle, you will never need any, because everything (and by that I really mean everything) can be typed. Either used libraries offer types directly or you just write them yourself.

Do yourself a favor and please never use any. There's no reason to and if you're unsure, use unknown, that's what the type is for.

Video gif. A cute grey tabby cat sits on her haunches with her paws together as if begging. Text, "Please."

Conclusion πŸŽ‰

I hope I was able to give you a little insight into TypeScript and show you how TypeScript can actively support you in writing better and more reliable code. I know it may seem like a hindrance at first, but believe me, since I've understood TypeScript and actively live it, I wouldn't want anything else.

In the next article about TypeScript, I'd like to show you how to deal with interfaces and how generic types can help you avoid duplicate code.