DEV Community

Cover image for TypeScript and why you should type your JS project
MiguelDevelopez
MiguelDevelopez

Posted on • Edited on

TypeScript and why you should type your JS project

TypeScript is like JavaScript but with no surprises.

I heard a long time ago about TS, great stories about how useful it is, allowing js to have Javascript types. At this moment I wasn’t so 100% aware of the sense of type everything, now that I have more knowledge about clean code, good practices and start to develop some little applications in React I think that the code could be better with types and I decided to investigate about and… this is what I found:

🥰DEVELOPERS LOVE IT

Here are some charts about how people start to use more and more…
image
More interesting charts about JS here: https://2020.stateofjs.com/en-US/technologies/javascript-flavors/
Increasing the usage in GitHub projects.
image
https://octoverse.github.com/

And high place in the 2020 developer survey of StackOverflow:
image
https://insights.stackoverflow.com/survey/2020#technology-most-loved-dreaded-and-wanted-languages-loved
Big companies like Airbnb support its use and claim that using it would significantly reduce potential errors.
image
Source: https://twitter.com/swyx/status/1093670844495089664/photo/2

I went deep into Reddit to find some real words about it and the same: “It's very hard to go back to Javascript once you start writing Typescript”.

🚄But… WHY ALL THIS HYPE?

With so many people loving it I decided to learn the basics and this is what I have learned that it can offer.

Advantages:

  • SUPERSET of JS, almost the same language but with consistency in types.
  • The main advantage is strict typing, you can type everything, from variables to the parameters of a function, and even the structure of an object, that's can prevent about 15% of the bugs that end up in committed code.
  • The ability to find these obvious yet frequently occurring errors this early makes it a lot easier to manage your code with types.
  • Types make code management easier and more predictable.
  • In TypeScript we can define interfaces for parts of our program, so we can be sure that they interact correctly. It means they will have clear contracts of communication with each other which will significantly reduce the number of bugs. TS + unit tests will do the code more stable, predictable and it will reduce the amount of pre-release bug density.

But… Not all that glitters is gold...

Some little disadvantages:

  • Apply type may make you slower in the first instance, in the long term it is better but you have to get used to it.
  • Required compilation.
  • And of course, TypeScript does not catch run-time type errors. It means that you can write the code that will pass the type check, but you will get an error upon execution.

🤖 Examples of SYNTAX

Basic typing when you declare variables, you won't be able to change the type later (even if you don't declare strictly the type it will be typed), making your code more reliable:
image
image
image
image
If for any reason, you need a variable without specifically type you can use any:
image
But... in the documentation, they recommend not to use it unless you are in the process of migration from JS to TS.
image
Add enum to JS, a way of giving more friendly names to sets of numeric values:
image
Typing parameters of a function will allow you to detect quickly if you insert something wrong
image
image
You can add what is the type of function that will return
image
image
but if you don’t do it typescript will do it for you
image
You can create your own types that allow you to don't repeat the code.
image
You can type also what you select from the DOM, allowing you access to all the methods of one kind of input.
image
There are also interfaces, a contract that should be matched with the object if you don’t want errors, and other
image
And of course, you can implement TypeScript into your favorite JS framework, I'll show you an example in a React project, providing the same advantages mentioned above:
image
Similar to the PropTypes and now you will have to add the props as mandatory when you use them or the IDE will warn you:
image
And when you introduce the mandatory prop person it will be okay:
image
You will be able to type other things (practically everything) like, for example, the hook useState:
image

And that’s it, folks, I hope you enjoy this little piece of info about TypeScript and maybe consider applying it in some project.

Here are some sources and interesting videos to check and go deeper if you want:
JSConf - Airbnb tactics and strategy to migrate to TS (very interesting)
https://youtu.be/P-J9Eg7hJwE

To type or not to type: quantifying detectable bugs in JavaScript
https://blog.acolyer.org/2017/09/19/to-type-or-not-to-type-quantifying-detectable-bugs-in-javascript/

Official documentation - TS in 5min to JS developer:
https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html

TypeScript tutorial series:
https://www.youtube.com/playlist?list=PL4cUxeGkcC9gUgr39Q_yD6v-bSyMwKPUI
In this video, you can see how to apply TypeScript in React:
https://www.youtube.com/watch?v=Z5iWr6Srsj8

Top comments (58)

Collapse
 
ssijak profile image
Saša Šijak

Then you just don't have experience of working on large enough plain javascript object. Jumping into such project and changing anything is a scary proposition.

Collapse
 
peppesilletti_4 profile image
Giuseppe Silletti

The only thing that will back you up when making changes is having in place some nice, solid automated tests.

 
patarapolw profile image
Pacharapol Withayasakpunt • Edited

I like to add typings in JSDoc (for JavaScript) and typings in Python as well.

You can do it to that level in TypeScript by setting noImplicitAny: false in tsconfig.json; and then, you don't have to always add typings.

But no, it's not the default settings.

To stray you away from TypeScript further, I would say that, typing in any dynamic languages (maybe apart from Dart and Julia), might give you a false sense of security. You should still write tests after that.

Still, I prefer to work with JS users who at least write JSDoc.

Collapse
 
matjones profile image
Mat Jones

TypeScript is like JavaScript but with no surprises.

Sorry but this is just utterly false for so many reasons.

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt

That's true. But then TypeScript is getting better.

The latest change is ability to make array and record indexing return undefined. (by settings in tsconfig.)

But yes, I will never trust TypeScript to be truly safe, nor truly strongly typed.

Collapse
 
matjones profile image
Mat Jones

Yeah, don’t get me wrong, TS is still a VAST improvement over JS.

Collapse
 
migueldevelopez profile image
MiguelDevelopez

and if you combine types and tests, will make the code reliable?

Thread Thread
 
matjones profile image
Mat Jones

If you have reliable enough tests, sure. And to be clear, I still think TS is a huge improvement over JS.

Thread Thread
 
johnkazer profile image
John Kazer

Having types of some sort helps me greatly in just writing functions, because it makes it much easier to remember just what data I'm messing around with. But I do tend to a functional/data-first style. So it reduces cognitive load way before you get to using tests/compiler to check things. And so, in fact, if your types are wrong your function/data manipulation will go wrong when you write it and a compiler/running tests are secondary things.

Collapse
 
johnkazer profile image
John Kazer

Could you list a few?

Collapse
 
matjones profile image
Mat Jones

Incorrect types for open source packages, happens quite often

If you’re targeting the browser... Internet Explorer

Generics not working the way you expect them to in certain scenarios

There’s lots. It’s also just a superset of JavaScript, so any surprise JavaScript can produce, typescript can also product.

Thread Thread
 
migueldevelopez profile image
MiguelDevelopez

Thanks for sharing these points, Mat!
I'll investigate the cons of using TS 🤔

Thread Thread
 
matjones profile image
Mat Jones

Don’t get me wrong, TS is a VAST improvement over JS, but it does have its own set of “gotchas”

Thread Thread
 
migueldevelopez profile image
MiguelDevelopez

To be honest, I don't use TypeScript yet, I just found it very interesting and loved by the community so... for that reasons I decided to write this, but I have in mind to start a little project to check his good points (and the bad ones too) 👏

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt • Edited

I use TypeScript (and Prettier) instead of ESLint and Babel, actually. And tsconfig is quite simple and intuitive.

Though, of course, you can use all of these together.

I wouldn't use uncompiled vanilla JS, as it is inconsistent between browser and node (as well as unminified and unfeatured).

So, if compiled anyway, why not TypeScript?

Collapse
 
akashkava profile image
Akash Kava

ts-ignore is superior to as any

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt

You can ban both of these with latest ESLint.

Collapse
 
akashkava profile image
Akash Kava

eslint-disable is superior to ESLint, its really difficult to catch unless you setup automated git monitor to track commit and warn usage of such features.

Thread Thread
 
patarapolw profile image
Pacharapol Withayasakpunt

Nonetheless, the idea of you CANNOT disable Golint sucks.

Collapse
 
migueldevelopez profile image
MiguelDevelopez

You diabolical...

Collapse
 
andreimoment profile image
Andrei Andreev

I appreciate your taking the time to write this article - it is a brief and clear introduction to TS.

And, I find the fact that you call a function that adds two numbers "minus" confusing to the point of disturbing. Would you consider fixing the example?

Also, after reading the article, I still don't know why "I should type my next JS project".

What are some common patterns where using typed JS is a benefit?

I get that other devs like it, but why?

Thank you!

Collapse
 
migueldevelopez profile image
MiguelDevelopez

Thanks for the constructive critic, I will update the advantages of TS to make it more clear with some examples and statistics about bugs

I reply to another dev to a similar question so I will copy-paste the answer:
Yes, I guess you are right, I miss the point of the title during the process trying to explain how simple is to write in TS instead of JS.
As you can see with TypeScript we can define the interfaces for parts of our program, so we can be sure that they interact correctly. It means they will have clear contracts of communication with each other which will significantly reduce the number of bugs. TS + unit tests will do the code more stable, predictable and probably will reduce the amount of pre-release bug density.

Any suggestion to improve the example related to the function minus?

Collapse
 
andrei_says profile image
Andrei Andreev

Hi Miguel, thanks for the reply.

  1. Name the function “add” so that it does what it says.

  2. What are some common places in a web app which benefit from typing and make the time investment of using typescript worth it? Examples?

Most of us don’t get type errors in our code. TS is a significant overhead. Why the overhead if no benefit? Adding busy work does not make me happy.

Why are all these developers so happy? Code examples where the extra hours of using TS actually save time?

Collapse
 
imsuvesh profile image
Suvesh K

After reading the whole thread my conclusion -
There are 2 types of people -
First - who likes TS / have used earlier and know how helpful TS is in Coding.
Second - Who don’t want to write extra pieces of code, So to justify their laziness they start giving excuses like Overcomplicated / Bloat / Better Alternatives / Example of closed projects.....

Nothing is perfect at the start, JavaScript also got multiple updates.
That's why we are developers, We evolve with time. If some new project comes that offers better than TS we will switch to it.
It's the same like - I will use Notepad because MS Word has spelling and grammar correction which is overcomplicated.

Collapse
 
abdurrkhalid333 profile image
Abdur Rehman Khalid

I started to use TypeScript when I learned Angular 4. At that time, I thought that I would be using TypeScript only for Angular Development, but as time progressed, the TypeScript found its way through the ReactJS and normal JavaScript Development as well.

I think the reason behind this is the strictness that do not allow the developer to get too flexible with JavaScript and allow the developer to write more readable and cleaner code.

Collapse
 
migueldevelopez profile image
MiguelDevelopez

Totally! That's one of the main advantages for me

Collapse
 
lesleyvdp profile image
Lesley van der Pol

Typescript is great in my opinion. I'm glad to be able to use it at my current client now. I do think the article focuses more on how you write typescript than explain why you should use it in your JS projects. Great article none the less! :)

Collapse
 
migueldevelopez profile image
MiguelDevelopez

Yes, I guess you are right, I miss the point of the title during the process trying to explain how simple is to write in ts instead of js.
As you can see with TypeScript we can define the interfaces for parts of our program, so we can be sure that they interact correctly. It means they will have clear contracts of communication with each other which will significantly reduce the number of bugs. TS + unit tests will do the code more stable, predictable and probably will reduce the amount of pre-release bug density.

Collapse
 
sebbdk profile image
Sebastian Vargr

Having types means needing to write less unit tests.
And they serve as documentation.

There's really no reason to not use a typed language.
Typing is not what developers spend most of their time one anyways.

Collapse
 
sebbdk profile image
Sebastian Vargr

Actually, thinking about this again, there is one very good reason not to use types. :)

For people that are just learning to program, learning types is less important than learning the mindset & how to debug.

Gotta walk before we can run. :)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.