DEV Community

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

Posted on • Updated 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 (102)

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
 
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
 
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
 
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
 
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
 
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. :)

 
patarapolw profile image
Pacharapol Withayasakpunt • Edited

It doesn't matter if I don't fully benefit from it, does it?

Don't be too serious and try to fight JavaScript.

Furthermore, I don't have a problem creating my .d.ts.

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
 
darthwalsh profile image
Carl Walsh

I really like JSDoc! I've used TypeScript for a few libraries but for projects that don't need a build step, it's so simple to just edit your source from the browser devtools source panel.

You can still check your project "compiles" by running the typescript compiler over our JS source by adding tsc -p jsconfig.json to your package.json like this. Here's my jsconfig.json -- the commented out rules fail now but it's on my backlog to clean up the code.

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
 
manelgonzalezops profile image
ManiloxGT • Edited

That fuctions could have been written by a child.
What about if you instead of providing such a ridiculous examples, shows us an example of how would you type a component generated from a render props that takes a function props that expects a ref as a paremeter?? Would typescript still be so fancy?

Collapse
 
peerreynders profile image
peerreynders • Edited

TypeScript advocates always seem to be up in arms when somebody suggests that they don't need types.

I'd like to turn the tables. I'm flabbergasted (well, not really - more like 🤦‍♂️) how people claiming to value static typing are championing a tool that eschews soundness.

No Soundness, No Business

Now Java dates back to 1995 and C# to 2000 but TypeScript didn't appear until 2012 - so what is TypesScript's excuse? Gradual typing of JavaScript code. So that is worth a tradeoff that essentially undermines the perceived "safety" of static typing?

Bottom-line - anybody who is actually serious about static typing wouldn't be using TypeScript for this exact reason but something more like ReScript (and simply accept the additional pain of JavaScript interop).

TypeScript is simply a super linter that requires syntax extensions to normal JavaScript (making it not parsable as JavaScript unless you stick to JS Doc TS) to do its job. TypeScript is a Subset of JavaScript - it's only a superset in terms of syntax but not in terms of capability.

TypeScript is popular:

  • because of IDE (VS Code) integration, most notably Code Completion. It's humorous how for years Java users have been denigrated by their peers for their reliance on IDEs to work around the warts and boilerplate of Java - and TypeScript/VS Code are gaining popularity and praise for those same features - TypeScript could only succeed because VS Code (and the like) made the additional ceremony bearable.

  • because it gives developers coming from Java/C# a false sense of familiarity - which is actually dangerous because they keep operating on a mental model that is something other than JavaScript, setting themselves up for disappointment.

And finally the term "strong typing" is almost meaningless:

Erlang is also strongly typed. A weakly typed language would do implicit type conversions between terms. If Erlang were to be weakly typed we could possibly do the operation 6 = 5 + "1". while in practice, an exception for bad arguments will be thrown:

i.e. Erlang is dynamically typed but considers itself strongly typed because it does not coerce types.

When people use the term "strong typing" they usually mean "static typing"; when they use "static typing" they feel "safe" even though that safety actually requires "soundness".

Yes, types improve code.

It's usually helpful to write down the type of new functions first;

But the primary benefit comes from thinking and designing in types, i.e. type-driven development. That can be practiced in a dynamically typed language - simply using a type-aware tool doesn't automatically yield those benefits.


Life After Business Objects

Collapse
 
suneeleng profile image
Suneel Simhadri

But finally all .ts files will convert into .js files so they can work in browsers.
Then what's the exact advantage of Typescript.

I have coded something in typescript,
Let a:string = 'some string';

And I tried to change that value using input[type='number'] tag.
Then 'a' value is changing even the given value is 'number'.

Can you please give me more brief about typescript?

Thanks

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