Why you should only use TypeScript ☝️
Tags: javascript, typescript, webdev, experiencereport
Published: 2023-12-30 19:02:52

![](https://blog.disane.dev/content/images/2023/12/why_you-should-only-use-typescript_banner.jpeg)JavaScript is dead, long live TypeScript! I explain how TypeScript actively supports you in writing better and more reliable code in this article 🎉

---

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](https://wikipedia.org/wiki/JavaScript). It is actually quite interesting and also shows why many people confuse Java and JavaScript or why it is called JavaScript.

[JavaScript - Wikipedia![](https://wikipedia.org/static/apple-touch/wikipedia.png)Wikimedia Foundation, Inc.Contributors to Wikimedia projects![](https://upload.wikimedia.org/wikipedia/commons/a/a4/JavaScript_code.png)](https://wikipedia.org/wiki/JavaScript)

### 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](https://en.wikipedia.org/wiki/Just-in-time%5Fcompilation)).

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](https://en.wikipedia.org/wiki/Integrated%5Fdevelopment%5Fenvironment) 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.

```js
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`.

```js
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:

```js
// 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.

![](https://media1.giphy.com/media/mq5y2jHRCAqMo/giphy.gif?cid=5a38a5a2u1wyxgldtljf29nf5l2t06yueo6qbuq6c5uz4gyq&ep=v1_gifs_search&rid=giphy.gif&ct=g)

### 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:

![](https://blog.disane.dev/content/images/2023/12/image-37.png)

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:

![](https://blog.disane.dev/content/images/2023/12/image-39.png)

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.

![](https://blog.disane.dev/content/images/2023/12/image-42.png)

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

![](https://blog.disane.dev/content/images/2023/12/image-41.png)

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

![nuclear explosion GIF](https://media2.giphy.com/media/oe33xf3B50fsc/giphy.gif?cid=5a38a5a2vkc4ro45uv9n57jrmfphdszzv1ol0eu33h1qo4zq&ep=v1_gifs_search&rid=giphy.gif&ct=g)

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.

```ts
// 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:

```ts
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 TypesThe language primitives.![](https://www.typescriptlang.org/icons/icon-192x192.png?v=8944a05a8b601855de116c8a56d3b3ae)Everyday Types](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html)

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](https://www.typescriptlang.org/tsconfig#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](https://www.npmjs.com/~types) 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."](https://media4.giphy.com/media/I1nwVpCaB4k36/200w.gif?cid=5a38a5a27cv24fe02gpobcv5z1233s0sk5z77sqyx0lhot4h&ep=v1_gifs_search&rid=200w.gif&ct=g)

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

If you like my posts, it would be nice if you follow my [Blog](https://blog.disane.dev) for more tech stuff.