DEV Community

Cover image for To TS or not to TS, that is NOT the question. Is it?
JoelBonetR πŸ₯‡
JoelBonetR πŸ₯‡

Posted on • Updated on

To TS or not to TS, that is NOT the question. Is it?

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 πŸ˜† 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.
You can laugh as much as I'm laughing at the time of writting that down πŸ˜†



The question would be:

Which are the main reasons to use TypeScript?

1. Type Inference

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.

2. Real-time type checking

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.

3. Interfaces

You are able to set up interfaces in TS by default whereas in JS you need some external lib like implement-js or validate a schema using validation libraries like Joi.



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.

How can we reach that?

We have 2 ways to use TS in our projects.

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.

// @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;
}
Enter fullscreen mode Exit fullscreen mode

Copied this code from my own comment on this post as example.

Which benefits do we get using TS Pragma and JavaScript?

  • We got documentation enforced by the workaround:
    Documentation inference

  • Type-checking in Dev Time:
    Type checking method
    Type checking function

  • Type inference (Even without explicitly declaring puppyWeight type):
    Type inference const
    Type inference const method

Of course the same happens with variables:
Type inference variable
Type inference variable method

We can also define variable and constant types with inline JSDoc like that:
Const variable type declaration

  • 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 ESLint plugin JSDoc.

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.

Cons:

  • This workaround does not let you use all features that TS brings. i.e. you can't use generics afaik.

Till next time! πŸ˜„

Do you like my content? β˜•Buy me a coffee


Still here? Pin this JSDoc Reference

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

Best regards

Top comments (63)

Collapse
 
paratron profile image
Christian Engel • Edited

I was strongly against TS not too much time ago. I hated it. It made me feel incapable of expressing my thoughts in code anymore. It prevented my from using JS as I was used to. My code worked stable most of the time and JSdoc helped a lot in adding types to functions and variables.

When i started using TS, I was constantly fighting the compiler which spit out long and complicated error messages.

Those days are gone now. I fought my way through and came to piece with TSC. I use it every day now and would not start any JS project without additional TS guidance.

About your post:
JSdoc is good and fine but it has its limits. I am much in favor for adding descriptive comments on top of functions but the type descriptions just dont cut it. The TS syntax is extremely more expressive.

I also have the feeling you are missing a lot of what TS can give. You mention for example that TS interfaces are only good for OOP. Thats wrong. You use interfaces to describe objects and their properties - and objects are passed around in JS all day. In fact interfaces are my most used feature of all.

Collapse
 
joelbonetr profile image
JoelBonetR πŸ₯‡ • Edited

Totally agree,

Editing the OP according to that!

my scope for the last year has been React and NextJS (plus few Node) so prop-types work best than adding TS interfaces as prop-types are checking in runtime plus it lets you define clearly which props are required, which ones are optional and in case they are optional, it makes you add a default.

In Node I usually use Joi which covers the same need.

About JSDoc limits... I don't think it really has many, check this out typescriptlang.org/docs/handbook/j...

Collapse
 
paratron profile image
Christian Engel

I am working in a similar environment (nextJS frontend for a huge news portal in germany).

We are not using prop types at all in favor of: typescript interfaces! :D

Ususally, a component looks like this:

interface Props {
    id: string;
    title?: string;
    count: number;
    currentUser: UserObject; 
}

function MyComponent({id, title = "Default", count, currentUser}: Props){
    ...
}
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
joelbonetr profile image
JoelBonetR πŸ₯‡

You can combine the JSDoc approach with PropTypes.
Remember that TS interfaces and Prop Types are not covering the same need.

Prop Types offer runtime checking while TS does not plus it lets you define optional and required props and enforces you to add a default for those which are optional πŸ˜€

Thread Thread
 
paratron profile image
Christian Engel • Edited

Runtime checking is absolutely unnecessary - except at the point where foreign data enters your system. So static type checks are better since they do not unnecessarily clog your runtime execution.

About optional and defaults: thats perfectly possible and I used it in my example. title is optional and has a default.

Thread Thread
 
paratron profile image
Christian Engel

Oh and by the way: as far as I know, the runtime checks of prop-types only work in development mode and is removed from production builds - so you get the sameas with TS.

Thread Thread
 
joelbonetr profile image
JoelBonetR πŸ₯‡ • Edited

In my current specific use case there is a headless CMS that manages both the structure and the data to show on it.

It's better to not remove them and fallback to a controlled error if it suits instead.
Removing them is something that you need to actively config, not something that works like that out of the box.

On the default thingy, we can receive relatively big chunks of data thus It's less invasive or more maintainable to get defaults defined in prop-types instead on the component definition.

It's all about the use-case like always :)

On the other hand, by all means this post is about having different options, not an allusion to fight between two tech stacks. You can use whatever you want, but you should use whatever your project needs.

A possible TL;DR would be "Is better to use TS, but just use the amount of TS you really need" πŸ€·πŸ»β€β™€οΈπŸ˜‚

Collapse
 
curiousdev profile image
CuriousDev

At least if we are about the question "should I learn JS or TS?", I would say, that it makes more sense to start with JS in case this did not happen yet, because TS just extends it. Regarding the usage, as you ask with this article, I guess TS should be preferred, if possible. Requirements can be fundamental knowledge about JS and having additional experience with TS.
There is still the option to switch from a JS project to a TS project, especially if you have well written code (but I do not have much experience to verify this at the moment). If this is not the case I would also doubt, that TS necessarily makes everything "magically" better. You still need to code carefully.

Collapse
 
joelbonetr profile image
JoelBonetR πŸ₯‡

I completely agree with that. It has been a mantra on the community that TS makes your code better but it simply can't be true.

Experience, practice and having enough time is what makes a better code and a better coder. I've seen with my two functional eyes big messes using different languages, frameworks and so and I've seen beautiful code in some of them (including vanilla JS).

Collapse
 
brense profile image
Rense Bakker

Yes it simply can be true. Because you can write the most horrible crap in JS and there's no compiler that will ever complain to you.

Thread Thread
 
joelbonetr profile image
JoelBonetR πŸ₯‡ • Edited

So in both JavaScript and TypeScript (and whatever language you can think off) you can:

And much more, (I repeat, with both JS and TS, in fact you can do the same in almost every language) but to you, it's the environments fault (language, IDE, compiler/transpiler/bundler...).

Most of this things can be enforced using ESLint, there's no way typescript will make you suddenly write good code. Practice, experience and a style guide will do.

Cheers

Thread Thread
 
brense profile image
Rense Bakker

Yes if you want to write unclean code, you can do so in any language. In Javascript however (and other code cowboy languages) you can write crappy code that will produce unexpected run time errors, that become an absolute nightmare to debug. This is something you cannot do in type safe languages.

Discussing principles of clean code as an argument in favor or against Javascript or Typescript is pointless, because clean code principles are language independent. Although there are differences in clean code principles between languages that are strictly OOP and languages that are strictly functional.

Thread Thread
 
joelbonetr profile image
JoelBonetR πŸ₯‡

Man, really...
Both ways to use TS in the post helps you in dev time.

If you want runtime protected code in both JS and TS need to control the errors in runtime explicitly (i.e. try-catch, somethingExists && somethingExists.doSomething() and so on).

TS will not magically help you in runtime and I'm sure you already know it.

Thread Thread
 
brense profile image
Rense Bakker

It does. I don't even remember the last time I had a runtime error... Yes if you want to you can explicitly throw a runtime error. In JavaScript you can never rely on any variable or function return to have the value that you expect, unless you're the only one working on the project, use pretend typescript (JSdocs) and you remember everything that you did 3 months ago. Me I'm a human and I work with other humans.

Thread Thread
 
joelbonetr profile image
JoelBonetR πŸ₯‡

The only way I got runtime errors (it doesn't matter if TS or JS) is when someone alters an endpoint and we receive something unexpected, you need to control the errors whenever language you are using.
That's because we work in a team. And we do mentorship to juniors, code review to the PRs and so on.

Thread Thread
 
brense profile image
Rense Bakker

Yes your team is obviously made of superhumans who never make mistakes, good for you.

Thread Thread
 
joelbonetr profile image
JoelBonetR πŸ₯‡

There's CR for that.
Man really, I've the feed full of your comments defending TS as the only thing that exists in the world.
If you want to use it for anything it's ok, it's your decision. Go ahead and don't bother the rest.

Thread Thread
 
brense profile image
Rense Bakker

Thats a nice way to twist things around. Except the only reason this started is because you keep bashing Typescript in favor of JSDoc. I've never felt a need to explain the advantages of Typescript over JSDoc before, because I've never met anyone like you πŸ˜‚

Thread Thread
 
joelbonetr profile image
JoelBonetR πŸ₯‡

So I make a post in which I say that some features that TS brings are a must, proceed to explain how to get TS in dev time as intermediate option, explain the benefits we get using this over JS and you feel like I'm "bashing TS". Ok I guess, whatever you say πŸ€·β€β™€οΈπŸ˜…

Thread Thread
 
brense profile image
Rense Bakker

Thats a nice way to twist your own post, which ends with explaning how to use your elaborate JSDoc approach instead of just Typescript. Something that you've been doing all over dev.to for almost 20 days now, first in commenting on other peoples posts and now making your own posts to again show people your JSDoc approach.

Need I remind you of some of your own words: dev.to/joelbonetr/comment/1ndm9

God damn! using TS as "good practice"... The post was good since I read such a stupid thing.

I encourage you to learn JS properly instead.

Yes, I'd say that qualifies as bashing. And also it shows that at that time, you didnt realize that Typescript is a superset of Javascript, or you didnt understand what "superset" means. Something I'm glad you've learned since then, atleast we achieved something.

Thread Thread
 
joelbonetr profile image
JoelBonetR πŸ₯‡

Of course and I will say the same again. Using TS does not qualify in "code best practices". Mainly because those practices are language-agnostic.

As a little pun: One of them is Document your code πŸ˜†

You can search from Tom Cargill online, he's the one credited with the Ninety–ninety rule that lead to a sort of standardarized checklist of code best practices.

Thread Thread
 
brense profile image
Rense Bakker

Summary of 'Clean code' by Robert C. Martin:
gist.github.com/wojteklu/73c6914cc...
Comments rules:

  1. Always try to explain yourself in code.
  2. Don't be redundant.
  3. Don't add obvious noise.
  4. Don't use closing brace comments.
  5. Don't comment out code. Just remove.
  6. Use as explanation of intent.
  7. Use as clarification of code.
  8. Use as warning of consequences.

1 through 4 are not met by your JSDoc approach.

Thread Thread
 
joelbonetr profile image
JoelBonetR πŸ₯‡ • Edited

That's clean code by Robert C. Martin, not Code best practices but well.
If you watched the videos from Robert C. Martin you'll notice that it was nice on a different era yet he repeated the same mantra for years.
Nowadays is somewhat utopic and unreallistic. We got devs that came from a 3 months code camp working together with people that completed an engineering plus a master. The amount of projects grow enough to get people working 50%-50% in two projects at once. You work on a project with Angular, then you jump to the next one in React, then the next uses Next Js and the other... as examples.

If you have a team full of senior devs with experience working together, aligned on a single styleguide, with a similar base-knowledge, focused on a single project, stack and environment and you are sure that they are not going to leave the project/company you can avoid comments and expect the code to be self-expanatory.

If one of those requirements is not met, you'll face issues sooner or later.

Collapse
 
patoi profile image
IstvΓ‘n PatΓ³

There is no "JS vs TypeScript". The real question is: Do you NEED TypeScript? I don’t think you need to use it every project.

We are not using TS in a big client application (Svelte + JSDoc + d.ts, more than 400 files), and it's ok.

More: youtu.be/xLDVfBUgD8U
Do TypeScript without TypeScript - Simone Sanfratello / NearForm

Collapse
 
joelbonetr profile image
JoelBonetR πŸ₯‡

I'll check it out, thank you! :)

Collapse
 
jzombie profile image
jzombie

Are you manually writing that d.ts file instead? If so, it would seem it would be easier to just write in TS to begin with and let it generate the d.ts for you.

Collapse
 
joelbonetr profile image
JoelBonetR πŸ₯‡ • Edited

Good question here! While d.ts serves the purpose of documenting CommonJS modules (module.exports), JSDoc aims to document JS code and can be used to provide type information in JavaScript files which, along with TS pragma (// @ts-check) will make VSCode to use TS to automatically search for type notations and type checks whenever you document a function, variable etc. With that notation, Including ES6 modules export.

Leaving that alone, JSDoc + TS Pragma is a safely approach (first step) to migrate a JS project into TS or, if you don't want to add TS as dependency into your project or your team has zero or near-zero experience with TS, you can use this to provide type notations plus type checks without actually coding in TS, just by documenting your code which is always good.

Thread Thread
 
jzombie profile image
jzombie

I have no disagreements with using JSDoc. I find it incredibly useful.

Manually managing a d.ts, however, I'm not sure about.

There's the potential of getting those types completely incorrect if manually managing that file separately.

I'd think that if the aim is to use d.ts without TypeScript, surely someone has written some sort of parser which could generate them from JSDoc itself.

At that point, I'd just recommend using TypeScript, however.

Thread Thread
 
joelbonetr profile image
JoelBonetR πŸ₯‡ • Edited

No no, that's nothing related with d.ts. It's just that writing JSDoc this way (check TS doc around JS Doc I linked before) and adding // @ts-check at the top of your JS files, VSCode will type check your variables, functions/methods and so on using TS behind the scenes.

Try it out quickly on a single JS file if you're curious so it will be more clear probably 😁

Collapse
 
drazisil profile image
Molly Crendraven

Lots of good resources in the comments πŸ₯°

Collapse
 
brense profile image
Rense Bakker

Do you have shares in JSDoc or something? Because you keep bring it up in nearly every post you make.

Collapse
 
joelbonetr profile image
JoelBonetR πŸ₯‡

Hey, I'm just showing that since some days ago. Since when documenting your code is bad? I agree in each pros/cons of a given tech that's something you really need to practice.
We can agree that TS is good, but you seem stubborn on TS being "the only way to go" for any reason.

Collapse
 
brense profile image
Rense Bakker

If you want type safe JavaScript (which is the case if your team is bigger than 1 person), typescript is the only logical way to go yes.

Thread Thread
 
joelbonetr profile image
JoelBonetR πŸ₯‡

That's the key point. Using TS on a way or another πŸ˜†

Thread Thread
 
brense profile image
Rense Bakker

No, your way is a work-around to not use actual TS, but JSDoc with ts-check instead, which is not the same thing (which we've already established), you need to learn how to write proper JSDoc and you cannot use some convenience features that TS has, like generic types or type intersection features.

Thankfully, atleast you agree that type safety is important. You're convinced your way is better and you dismiss any arguments in favor of using just TS (which is nothing more than vanilla JS + type safety) it does not look like we're ever going to resolve that.

Thread Thread
 
joelbonetr profile image
JoelBonetR πŸ₯‡ • Edited

Gosh are you like a fanboy or something?
Each project has it's needs. There are tones of JS projects, is the most used programming language in the entire planet. TypeScript was released in 2012, it's been almost 10 years by now, but do you really know it's market share?

If you're about to create a npm package you probably will add TS or d.ts at least to bring extra-compatibility, that's a thing.

On the other hand, I'm gonna show you a real life metric:
Job offers naming JavaScript in the European Union (remote filter On):
Javscript job offers in the EU
Job offers naming TypeScript in the European Union (remote filter On):
typescript job offers in the EU

That's a huuuge difference of 43.275 (~5.5 times more in favor of JS).

Let's look at United States (remote filter On):
Javascript job offers in EEUU
typescript job offers in EEUU

The diference is even bigger here, 153.011 (~7 times more in favor of JS).

Even that, you are suggesting learners to learn TS without learning JS first and stupid things like that.

What will you say? that companies using TS don't use LinkedIn? πŸ˜† They suddenly hate microsoft so they decided to not using it's platform but keep working with TS? C'mon.

Do you really think that all those companies will suddenly migrate to TS for any reason? Are you that kind of utopic people that tries to change the world while refusing to learn how it actually works?

I can in fact get type intersection with this workaround and I do not need generic types most of the time or in 99% of my projects (either be personal or professional). Again, if you want this features, add TS and go ahead.

There are tones of posts telling people how good TS is since it has been released, still the amount of projects using it is low in comparison with projects that are not using it.

If I reach 3k people, they share this and they begin documenting their code and using some few features like type-checking in dev time, Welcome! We'll probably face better projects in a future.

Having people to know this one, the one that @patoi suggested or any other intermediate option is firstly a fact -because they exists- and secondly can be convenient for many.

It's ok if you don't share this feeling or preference but at least you can make the effort to understand it.

Thread Thread
 
brense profile image
Rense Bakker

Again, Typescript is a superset of Javascript. If you know Typescript, you can also apply for Javascript positions and nothing bad will happen. Except you'll have to deal with more runtime errors in production, which more and more companies are realizing is bad and costs them money.

You want to use your own method of preventing runtime errors thats fine I have very strong doubts that it is as effective as you say it is in a large software team (see all previous arguments that you chose to ignore). Unfortunately (or luckily) I have not encountered any large teams that used your method, so I cannot disprove your claims with hard numbers. Most teams I've worked in are comprised of humans who are sometimes lazy and make mistakes, which is why we chose not to rely on doc blocks for type safety.

Thread Thread
 
joelbonetr profile image
JoelBonetR πŸ₯‡

I you really want to know how it works, how it uses TS and so I can nicely explain more details. Some of them I already know others I may need to do extra-research.

I'm used to work with little teams (4 to 5 in frontend, 4 to 5 in backend, a couple in Data, infrastructure...).
We used TS in the project I was working on before and we have this approach on the current project. I've the role of tech lead/lead dev and I waited 8 months before posting this.
This post would have happened anyway but with two possible conclusions:
1- That's awful, let's migrate to TS and run.
2- That's actually nice, it covers the project needs.

And happened that was the 2 and here we are.

Another issue nowadays is the high demand of developers due to a low offer, and believe it or not, the amount of people that can code fluently with JS is notably bigger than the people that can do the same with TS.

The lack-of-devs issue in backend is also worrying, probably more than in frontend but still I feel that one of the benefits of microservices is not being addressed by the companies: Using different programming languages depending on the service.

I myself offered to code the gateway in Node JS but they prefer to keep all the backend in Java Spring. Now we need another Java Spring dev and finding one is lasting more than what I would like πŸ˜…

Thread Thread
 
brense profile image
Rense Bakker

"Another issue nowadays is the high demand of developers due to a low offer, and believe it or not, the amount of people that can code fluently with JS is notably bigger than the people that can do the same with TS."

Thats factually impossible though. If you can write fluent Javascript you can write Typescript (again, Typescript is a superset of Javascript). Javascript code is valid Typescript code (atleast before type checking).

You are right though, there is a lack of people with Typescript experience, however, there's an even bigger lack of devs who know JSDoc. So if it was your goal to cater to a larger pool of experienced devs, you failed (do that thing again on linkedin where you search for job offers, but this time with JSDoc πŸ˜‚)

When companies cannot get on board with new technologies, even though they have a lack of devs who can maintain or build their Java crap app (Spring), thats usually when I end my contract with that company.

Thread Thread
 
joelbonetr profile image
JoelBonetR πŸ₯‡

Empirically tested it and it's not so easy to get people used to JS to use TS, it's learning curve is higher.
With JSDoc it was like "Oh it works like that, pretty straightforward, Ok".

By the way... why a Java Spring App should be crap? Don't you consider Spring as valid tech nowadays? I'm curious about that point

Thread Thread
 
brense profile image
Rense Bakker • Edited

Valid tech... what is your definition of valid tech? I did not enjoy working with Spring Framework at all. Granted it was probably less bad than "vanilla" Java. It's been a long time since I touched anything related to Java though, maybe it got better? I doubt it though...

Empirically tested it and it's not so easy to get people used to JS to use TS, it's learning curve is higher.

Thats not my experience at all. But it probably depends on how you introduce Typescript, if you false tell people that it's a completely new language that they have to learn I'm sure it will look daunting going through all the Typescript feature docs that you don't need as a beginner. It becomes a lot easier when you explain to people that their Javascript is essentially already valid Typescript code.

Thread Thread
 
joelbonetr profile image
JoelBonetR πŸ₯‡

There are people in the company that has been explicitly hired to teach and it's the first stage whenever someone wants to learn something new. I bet they do it better than I do.

Collapse
 
jwp profile image
John Peters • Edited

TypeScript was the best thing to happen to Javascript. It had features many years before Javascript Integrated them.

TypeScript is still years ahead of Javascript IMO.

Collapse
 
joelbonetr profile image
JoelBonetR πŸ₯‡

Sure it has! The key point is to discern whether you need those features or not on a given use-case.

I'm currently testing some differences with an end-to-end javascript app (Node JS + React) to see if I can find specific use-cases that can bring a real competitive difference between both approaches mentioned on the post :)

Collapse
 
joelbonetr profile image
JoelBonetR πŸ₯‡

So we understood that we need TS (I guess) the question you need to answer when starting a project is "How are we going to use TS on this project"?

Thoughts?

Collapse
 
brense profile image
Rense Bakker

ts-check + JSDoc !== Typescript

You lose all the power that Typescript offers like generics and type intersections and to do anything but the most basic stuff, you have to deep dive into JSDoc and learn a whole new language. Then when you have it all set up, some jackass comes in and forgets to update a JSDoc after changing a function and your code just falls apart like a house of cards.

Collapse
 
joelbonetr profile image
JoelBonetR πŸ₯‡ • Edited

// @ts-check is from TypeScript pragma, it makes VSCode use TS to validate your code (to explain it on a simplified way).

Didn't read the post, did you? You can enforce it with the ESLint plugin JSDoc.

By the way:
type intersections JSDoc

On the other hand you're right with Generics, you cannot use them with this approach as far as I know.

Last but not least, it's somewhat worrying that you consider JSDoc (The standard way to document JS and TS code) a whole new language πŸ˜…

Thread Thread
 
brense profile image
Rense Bakker

Yes lets discuss what you consider a language. JSdoc has a learning curve. Its worrying that you would try to deny that or didnt get that point.

Collapse
 
j0shyap profile image
Josh Yap

Would you recommend a beginner/hobbyist developer learn TS from the start?

Collapse
 
joelbonetr profile image
JoelBonetR πŸ₯‡

TS is an addition to JS so if you're at the beginning of the road I'll suggest to learn JS beforehand. The same way I'll suggest to learn JS before jumping into React i.e.

Collapse
 
brense profile image
Rense Bakker

Learn Typescript from the beginning, because it means you also learned Javascript. Typescript is only a superset of Javascript. If you can write Typescript code, you can also write Javascript code.

Collapse
 
joelbonetr profile image
JoelBonetR πŸ₯‡

TS is a good addition to JS, but there's no tech to rule them all. There are few disadvantajes on using it:

  • More initial setup.
  • Additional learning on top of JavaScript is required.
  • Larger compilation/transpilation times.

We need to be honest about what we use. Knowing the good and the bad things of what we use helps us improving our work, fanboying something usually tends to a blid-following which is usually not good.

Thread Thread
 
brense profile image
Rense Bakker

The first 2 are true for JSdoc as well, with the disadvantage that JSdoc does not enforce type safety. If people forget to update it, your code will fail in runtime.

Compilation time (in milliseconds) is a very small price to pay for actual type safety. It saves me many hours of trying to debug a JavaScript runtime error.

Thread Thread
 
joelbonetr profile image
JoelBonetR πŸ₯‡ • Edited

1- I'm not saying that TS is bad in any piece of this texts.
2- JSDoc is PART of JavaScript, hence of TypeScript.
3- No, you can't have outdated docs with TS-Pragma, it will take care of that plus you can use ESLint JSDoc plugin just like you do in any project.

Thread Thread
 
brense profile image
Rense Bakker

1 - no you just spread false info about TS in an attempt to make it look worse than your beloved JSDoc.
2 - Comments are part of JS, JSDoc is a specific way of formatting your comments so that they can be interpreted. Thats definitely something you need to learn.
3 - or you can just dump a tsconfig in your JavaScript project. Do npm i --save-dev typescript and voila. Suddenly all your JavaScript code became Typescript code and you can benefit from type safety. Commit it and your whole team benefits from the same type safety.

Thread Thread
 
joelbonetr profile image
JoelBonetR πŸ₯‡

Sure you can use TS as dependency in your project. If you read the post it's written on it. JSDoc REQUIRES TYPESCRIPT to work for that type checking, again is explained in the post, using TS Pragma.
TS has more features than what you can reach with TS Pragma + JSDoc but most of the mortals don't always need those features, that's the key point on that. Is a less strict, hence more flexible way of having type-checking, inference and so. Again, it's explained in the post.

Thread Thread
 
brense profile image
Rense Bakker

Except your JSDoc approach is not more flexible. Everyone on the team will have to atleast learn the basics of JSDoc. Usually that doesn't happen though and people just copy paste doc blocks from other parts of the code, forget to change it and create a gigantic mess. If you need less strict typings, you should probably ask yourself why. What kind of mess are you trying to create?

The Flexibility that you speak of is something that Typescript does provide and exactly what makes it so powerful. Because it is a superset of Javascript, every developer who knows Javascript can start using it, without having to learn anything. The only difference is that Typescript is a Javascript flavor that doesnt allow you to create a mess, like having a function getCat that returns a Cat and then later using that result as if it's a Dog (aka type safety). Devs on the team who have more experience with Typescript features, can apply their knowledge to provide properly typed functions/libraries for the rest of the team to use. When team members are curious about how to type things more efficiently (which happens often when they stumble upon things during code reviews), you can plan an afternoon with them and explain Typescript generics or other features to them.

To me, the JSDoc approach just looks like at some point you wanted to use Typescript, but when you did, Typescript told you that some of your code was not type safe and instead of accepting that and learning how to fix it, you decided to look for a way to convince yourself you didn't do anything wrong.

Thread Thread
 
joelbonetr profile image
JoelBonetR πŸ₯‡

you can do all those things except for generic types with the approach suggested in the post and none of the issues you try to bring upon the table are right.
Why don't you create your own post praising the goods of TS instead bothering on other's posts with things you didn't even tested?

Collapse
 
domiii profile image
Domi

Is this a "pros + cons", because I think, the cons are missing? TypeScript, while great in many ways, also has its dark side, or at the very least, a learning curve with some rough edges (and for some reason, it is barely ever even brought up).
In short: Would you address this question? - "What did you find most frustrating about TypeScript, especially after you already used it for a while?"

Collapse
 
joelbonetr profile image
JoelBonetR πŸ₯‡ • Edited

This would be a different question. The post is more about letting people know that there are two different ways in which you can use TS in your project.

Type-checking, documentation and type inference in Dev Time is a valuable bunch of things to have, there's no doubt on that (I guess).
Being able to get those things while working with JavaScript just by adding TS Pragma and documenting your code (which is something you should want as well in your projects by default) suits for many projects.

If I'm going to create a big service in Node RE I'll probably add TS as dependency, but I'm not adding it in frontend React or Next JS applications because this other way to get type checking in dev time suits better IMHO.
This is just my personal preference without context and I myself can review my preferences in a future.

Knowing both ways to use this, you can choose whichever suits best for your projects.

I'm currently hands on two different projects using this second option, both are usign Next JS as framework but with two different approaches.
In the first one we depend on a headless CMS so the requests goes through Next -> gateway -> microservice -> CMS to get the page structure and data to pre-render it (SSR) with React, so the Node JS part in Next is just a middleware. (The GW and the micros are built with Java Spring).

The second one has it's own services inside Next JS Node part, connected directly to a database using Sequelize as ORM and Joi for validations.

If we need to migrate to TS for any reason (it doesn't look like to me) we can do it easily as we already defined types and so on.

I can extend more the architecture explanation but with the information provided you can see that the project with the CMS does not fit well for TS (we can receive whatever structure from the CMS and we should then define all the input types which is kinda annoying when client wants the things ASAP) so we can just use types for our inner components and ignore them in the dynamic factory that loads components dynamically to just check the identifier of each, or in other words, apply responsibility delegation.

Collapse
 
brense profile image
Rense Bakker

The most frustrating part about Typescript is that you cant write the bad code anymore that you used to write in Javascript :P

Collapse
 
joelbonetr profile image
JoelBonetR πŸ₯‡ • Edited

πŸ˜† πŸ˜† πŸ˜†
Sure you can, just like in any language!

Collapse
 
jderochervlk profile image
Josh Derocher-Vlk

TypeScript was a great way to slowly add types to existing legacy projects, and it's decent for small apps, but it breaks down in speed when you hit 100k lines of code with 40 devs. One person drops in a 'ts-ignore' comment or a as unknown as string and it starts to not be worth the effort.

I've made the switch over to ReScript and it's a much better alternative for writing strongly typed code that compiles to JavaScript.

rescript-lang.org/

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