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

Latest comments (58)

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
 
sempsei profile image
sempsei

verry good dude

Collapse
 
lyrod profile image
Lyrod

Any one knows this font?

i.imgur.com/mUUZcnU.png

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

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
 
andrewbaisden profile image
Andrew Baisden

TypeScript is going to gain more popularity this year.

 
zhnedyalkow profile image
Zhitomir Oreshenski

Well, most of projects are with ts. Almost each framework has ts integration as well.

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.

 
peppesilletti_4 profile image
Giuseppe Silletti

Hey man, if you need to introduce a whole new language only for catching typos, good for you! I'll keep using the eslinter

 
peppesilletti_4 profile image
Giuseppe Silletti

Where did I write that?

Anyways, at least for TS, having the right static type doesn't mean having the right runtime type. So you need to write tests for that. And those tests will also catch the same bugs that the compiler could catch.

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