To TS or not to TS, that is NOT the question. Is it?
Tags: javascript, typescript, discuss, devjournal
Published: 2022-04-26 17:46:16

There's like a fight or something like that about JS vs TS and I always like to go against TS in TS posts and against JS in JS posts. This way I get solid sentences about pros for one or another.
This makes me look like a troll but most of you guys only put a good amount of attention when you read something that bothers you or that is against your believes :laughing: be honest and don't blame me much for this (please).

I'll try to recap things straightforward and give you a good option as middle point in a vague try to stop that war from now on.
<small>You can laugh as much as I'm laughing at the time of writting that down :laughing:</small>

<hr />
The question would be: 
<h1>Which are the main reasons to use TypeScript?</h1>

<h3>1. Type Inference</h3>
Type inference is the automatic deduction of the data types of specific expressions in a programming language.

It works when calling a function/method so the IDE knows how many params does it need, which type they should be and will complain if there's something wrong.

It also lets you hover your mouse over the function name and you'll get inferred information about this function/method like the params and it's types, what it returns and so.

<h3>2. Real-time type checking</h3>
When you have an object in JavaScript, you can access every property of that object either the object having this property or not. 
This can lead to errors that are difficult to debug. In Typescript, your IDE tells you in real-time that you are trying to access something that doesn’t exist or that lacks this property or if you try to use some non-compatible method/function on it.

TypeScript always points out the compilation errors at the time of development (pre-compilation). Because of this getting runtime errors is less likely, whereas JavaScript is an interpreted language.

<h3>3. Interfaces</h3>
You are able to set up interfaces in TS by default whereas in JS you need some external lib like <a href="https://www.npmjs.com/package/implement-js" target="_blank" alt="interfaces in JS">implement-js</a> or validate a schema using validation libraries like <a href="https://www.npmjs.com/package/joi" target="_blank" alt="joi npm">Joi</a>.
<hr />
Ok so we all **understand and agree** that the points 1 and 2 are a **MUST**. 

Can we all -please- agree as well on the sentence **"to reach this in JavaScript (nicely) we need TypeScript"**?

Ok, let's move on.

<h3>How can we reach that?</h3>

<strong>We have 2 ways to use TS in our projects.</strong>

**1-** One is to add TypeScript as project dependency, perform the setup and start coding. You all know about that or you can find tones of information about this online so I'm not extending on that.

**2-** The second one is to use **TS Pragma** in your JS files along with **JSDoc** and enforce the overall with a linter like ESLint. 
VSCode will handle that out of the box in real time. Zero config needed.

```javascript
// @ts-check

/**
 * Calculates the total weight of the inventory
 * @param {string} inventory
 * @returns {number}
 */
function inventoryScore(inventory) {
  let totalInventory = 0;

  inventory.split(',').forEach((item) => {
    totalInventory += getItemWeight(item.trim());
  });

  return totalInventory;
}

/**
 * Retrieves the weight of a given item
 * @param {string} item
 * @returns {number} weight of the item
 */
function getItemWeight(item) {
  if (item === 'gold cup') return 5;
  else if (item === 'puppy') return 4;
  else if (item === 'magic cup') return 10;
  else if (item === 'tooth of a magestic whale') return 20;
  else if (item === 'tentacle of a giant squid') return 100;
  return 0;
}
```

Copied this code from my own comment on <a href="https://dev.to/laryken/what-am-i-missing-please-it-doesnt-give-me-the-total-it-only-evaluates-the-first-if-5cld" alt="issue help post" target="_blank">this post</a> as example.

<h4>Which benefits do we get using TS Pragma and JavaScript?</h4>

- We got **documentation** enforced by the workaround:
![Documentation inference](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w7u80rf0j4cq86vj3dpc.png)

- **Type-checking** in Dev Time:
![Type checking method](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8x2hxra7t1kmbxxuoysg.png)
![Type checking function](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n25s13dm8m9pi4jhk6s0.png)

- **Type inference** (Even without explicitly declaring `puppyWeight` type):
![Type inference const](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pfxqzz8dvdz0calir2bl.png)
![Type inference const method](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oyim9lynwj0p0eol5ywm.PNG)

Of course the same happens with variables:
![Type inference variable](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/822bccgb2v23mygtce96.png)
![Type inference variable method](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lsmu32ovfh7qv8c3euhy.png)

We can also define variable and constant types with inline JSDoc like that:
![Const variable type declaration](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x2i5vwfjq8fyd3x1z3v2.png)

- We also avoid the **extra-build time** that adding TS as dependency causes.

For those thinking on "yeah but people will refactor things and forget about documentation", well, TS Pragma will use TS behind the scenes to ensure it's OK plus we have a linter, so we can use it. Check the <a href="https://github.com/gajus/eslint-plugin-jsdoc" alt="eslint plugin jsdoc" target="_blank">ESLint plugin JSDoc</a>.

As extra benefit, this approach can serve as introduction to TS, getting yourself used to declare types and forcing you to document your code (which is always good).
If you want at any point and for any reason to migrate your project from JS to TS it will be much easier.

<strong>Cons:</strong>
- This workaround does not let you use all features that TS brings. i.e. you can't use generics <strong>afaik</strong>.



Till next time! :smile:
<img src="https://c.tenor.com/Cnx-ruNoo1AAAAAC/jetpack-japanese.gif" />

Do you like my content? ☕<a href="https://www.buymeacoffee.com/joelbonetr">Buy me a coffee</a>

<hr />

Still here? Pin this <a href="https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html" alt="jsdoc reference handbook" target="_blank">JSDoc Reference</a>

Will you take a try to this approach? Let me know in the comment section

Best regards