DEV Community

Cover image for To Typescript Or Not To?
Akash Shyam
Akash Shyam

Posted on • Edited on

To Typescript Or Not To?

In my previous post, one of my readers, said some very good points against typescript and is resulting in a pretty long conversion in the comments. So, I'd like to do have a final comparison.

Advantages of Typescript

  1. Strict Typing

Once declared, a variable can take only one type and can take only certain values. The compiler alerts developers to type-related mistakes, so they have no opportunity to hit the production phase. This results in less error-prone code and increase in developer productivity.

For example, we call a string specific method on an argument, we can do this without need to add an if check because typescript will through an error if a different type of value is passed.

But static typing is not only about catching bugs. It also gives the code more structure, makes it self-documenting and more readable, speeds up debugging and refactoring.

It’s important to note that TS doesn’t force declaring types everywhere. Developers are free to change the level of type strictness in different parts of the project. This approach distinguishes TS from other statically typed languages and allows you to find the right balance between flexibility and correctness. This also makes it easy to migrate javascript code to typescript because we don't need to convert the entire code base to compile the code.

With TypeScript, everything stays the way it was initially defined. If a variable is declared as a string, it will always be a string and won’t turn into a Boolean. This enhances the likelihood of functions working the way initially intended.

  1. Early spotted bugs

Researchers found that TypeScript detects 15 percent of common bugs at the compile stage. Far from a 100 percent result, this amount is still significant enough to save developers time and let them focus on correcting mistakes in the logic — rather than catching common bugs. Pushing the code through a compiler also decreases the volume of quality assurance and testing activities.

  1. Sweet VS-Code Autocomplete
    Vs code already has great javascript autocomplete but typescript gives it an enormous boost. Also, if we use external 3rd-party libraries, we can check the type definitions which will be faster than checking the docs(some libraries don't have great documentation)

  2. Extra Features
    Over and above the normal javascript features, typescript has several features which are not in javascript. For example, public, private and protected fields, Generics which helps us to create quite complex dynamic typings, Nullish Coalescing (??) etc], abstract classes.

  3. Popularity

Typescript has over 19 Million weekly downloads on NPM:

Screenshot 2021-07-27 at 15.09.56

Next, let's look at the 2020 survey from the state of js, one of the most popular Javascript surveys.

Popularities of Various JS flavours over the years:
![ScreenshotScreenshot 2021-07-27 at 15.17.31

Percent of people who like/dislike typescript:

2021-07-27 at 15.16.31

Experience Over time:

Screenshot 2021-07-27 at 15.21.25

According to the [2020 SO survey], typescript is the second most loved language, surpassing python too! (https://insights.stackoverflow.com/survey/2020):

Screenshot 2021-07-27 at 15.24.45

Of course, these are just numbers. Popularity doesn’t necessarily mean that something is of high quality and should be trusted. Fortunately, TypeScript also enjoys support from some truly formidable players in the tech world.

The language is widely used in software products such as Slack, Medium, Asana, or Visual Studio Code. What’s more, many great JavaScript tools are written in TypeScript, including frameworks (Angular, Ionic etc) and libraries (ZoomCharts, yWorks, or GoJS).

As if that wasn’t enough, tech giants like Microsoft (duh!), JetBrains, eBay, Ericsson, airbnb or Ubisoft are all open about using TypeScript—and who knows how many other enterprise-level companies have included it in their tech stack.

Disadvantages Of Typescript

  1. Extra Stage - Transpiling
    One of the major argument against TypeScript is that it requires compilation, while JavaScript doesn't. But, let’s be honest, most of JavaScript applications these days require a build step. Whether it’s Gulp, Grunt, Webpack, Rollup, Babel, or Closure—a build step is a necessity and nothing really prevents you from expanding it.

  2. Extra code
    To leverage the features of typescript properly, we need to create types, interfaces etc and under a time constraint or a tight deadline, this may cause unnecessary delay. However, in the long run, it will save us a lot of time because a new developer will need a lot less time to understand the codebase.

  3. Learning curve
    Even though typescript is similar to javascript, there is still some learning that needs to be done to understand the code properly.

Conclusion

I think that this is subjective, and as person who loves autocomplete, code readability and syntactic sugar (and a person who introduces a lot of bugs 😅) typescript is the obvious choice for me. However, while working on a tight deadline, vanilla javascript would be better

If you liked this post don't forget to leave a like and follow me here on dev.to and twitter where I will (try) to post javascript/typescript tips and tricks regularly. Bye 🤟

Top comments (87)

Collapse
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

I'll give you 8 reasons (that can be a post itself) for NOT using TypeScript:

1- It is risky

How can it be risky if TypeScript adds type definitions and checks them at compile time and IDE integration will warn you about any type mismatches?

Exactly because of that. TypeScript will only check types at compile time and only types that are available. Any network calls, system libraries, platform-specific APIs and non-typed third-party libraries have no way of communicating with TypeScript. As you get used to having your types checked and not having to fully understand the code and the platform, errors and bugs will manifest themselves.

With JS, you make no assumptions about types, and you check the concrete value of the variable to make sure it is what you expect it to be. Or, if you do not care about its type in this particular case, you do not. In TS, you rely on the compiler to do it for you.

You can combine the two ways, but what is the point then? If you will spend time writing definitions and then spend time writing code to ensure these definitions are maintained during runtime, why have them in the first place? You can do the same in JS defining your type-checks and the result will be the same but clearer.


2- It is messy

Another paradox: the language that was supposed to bring clarity and readability to the codebase obscures it instead. To show you what I mean, check out some of these examples I found in popular open-source libraries:

// TODO: do this more elegantly
;((currentReducer as unknown) as Reducer<
  NewState,
  NewActions
>) = nextReducer

This one is from the Redux library, and all these 4 lines do is assign nextReducer to currentReducer.

Next example if from the RxJS library. I do not know about you, but if I have to fight a tool that is supposed to help me, I do not think this is a good tool.

// HACK: Since TypeScript inherits static properties too, we have to
// fight against TypeScript here so Subject can have a different static create signature
/**
 * Creates a new cold Observable by calling the Observable constructor
 * @static true
 * @owner Observable
 * @method create
 * @param {Function} subscribe? the subscriber function to be passed to the Observable constructor
 * @return {Observable} a new cold observable
 * @nocollapse
 * @deprecated use new Observable() instead
 */
static create: Function = (subscribe?: (subscriber: Subscriber) => TeardownLogic) => {
  return new Observable(subscribe);
}

3- It does not solve the problem

TypeScript is said to solve JavaScript’s problems. But it does not. Dynamic typing was never a problem in JavaScript, but many other gotchas such as NaN === NaN being false, semicolons being optional or not optional, a linebreak changing an object definition into a scope, syntactic sugar in place of OOP are indeed problems. TypeScript does nothing to solve them, but introduces yet another standard, further polarizing the JS community.

Even under the assumption that the lack of typing in JS is a problem, TS does not solve it. Do you know what does? Java, C, C# and other compiled languages. They can safely guarantee strong typing at compile time and runtime. Interpreted languages are just not capable of it.


4- It is not a superset, it is a subset

TypeScript is something that compiles into JavaScript, it cannot be a superset by definition. It limits what you can do with JavaScript and obscures its strong sides while providing a fake peace of mind. If you really want to be a great developer, do not settle for a comforting lie and try to understand the true power of JavaScript and its flexibility.


5- It is open-source, but nothing more

Many reasons for using TypeScript state that it is open-source. That is true, TS compiler is distributed under MIT license. But it is still controlled by Microsoft, a giant monopolistic corporation, and its open-source advancements are nothing but a marketing move. Do not confuse open-source with democracy: Microsoft is still free to do anything they want with TS, and you are just here to watch. JS, on the other hand, is governed by an international committee and will not change anything without the community’s approval.


6- But big companies use it…

I cannot believe that some people consider this a reason. Big companies also use legacy codebases, commit tax frauds... Why all of a sudden some of them using TypeScript is a good example? Unless of course you want to work on a given one, but this can be applied to any programming language or framework and maybe when you end up learning how to use a tech stack they switched to another so... is it a good reason?

Apart from that and if you still consider this as a reason, you can find much more companies using JS than using TS.


7- But it has more features…

Not anymore. True, when TS was first introduced in 2012, it had features like classes, still not available in JS by this time. But JS had come a long way since then, and now TS is struggling to keep up. If there is anything missing in JS, there is a babel plugin to do it.


8- It hurts the development time

As you said it adds transpiling time which is something that you definitely don't want. Most companies choose JS (or PHP or Ruby or...) for being interpreted languages which means you avoid compiling/transpiling every single time and you end up with faster development.


Conclusion:

If you really feel in need to get strong typing you just need to search "strong typing js babel plugin" and you'll find many approaches that can fit for you or for your project.

A previous analysis for the project needs hardly will throw as output that you need TS thus I would not recommend using it from now on, JS evolved fast and there are no reasons to use TS since time ago.

If you really really think that TS default features are what you need always, then use Java for example, in which you can handle both sync and async operations and you'll have a real strong typing and that all.

If you grab the popularity metric, TS has nothing to do in this fight. You can search wherever you like and you'll find out that JS have more popularity for obvious reasons. TS needs JS, but JS don't need TS.

And finally and probably the most important thing:

You bring the "Early spotted bugs" sentence with corresponding explanation.
But a thing that makes a piece of software reliable are not the language it's built with but the TESTS.
If you jump into a 4 years old application that grew and grew and it's still growing no matter which language it's used to code it. You'll need eventually to refactor things and if you are afraid of the code, maybe of your own code and you don't want to edit the current code because "it's working" is because you can't trust the tests (if any). If you can trust the tests is easy to refactor things and end up with a "hey, the tests that I know and trust that cover 100% this are passing without errors, so my refactor is nice".

This is what really brings bugless applications, a good approach as architecture is TDD which ends up with a -usually- better result than first coding whatever and lately coding the tests and this is why you should avoid to put "bugs" as language fault because they rarely are a language's fault, but implementation issues, bad practices/habits and so on

Collapse
 
jackmellis profile image
Jack

Just addressing the very first point as this is no different to any other strongly-typed language. When you have to deal with external sources and boundaries in any language, you don't have type safety to support you. You must always sanitise your external data. The point of TS and any strongly-typed language is that once you've validated your incoming data at runtime, you can be pretty confident that your data types in your own code are correct. If you feel like typescript doesn't give you more confidence in your own code then isn't that more of a statement about your confidence in your own ability to write clean code?

I got to the second point about messiness where you trawled and found 2 very specific examples of typescript being awkward (which could also probably have been solved in cleaner ways than that!). I can't say I've ever had to write anything like that in the last 4 years. And when I have had to "hack" typescript, it was usually because I didn't understand what I was doing at the time. If anything, when I have to work with vanilla js now I find it much harder to follow because I don't have any way of knowing what argument types are or what a function's return type is.

A lot of this post feels like classic stubborn anti-typescript attitude that I have fought against for years, and probably the same attitude I had myself at one point.

Collapse
 
webbureaucrat profile image
webbureaucrat

I'm firmly Team TypeScript and Team Static Typing, but there's a definitional problem here I want to flag.

Just addressing the very first point as this is no different to any other strongly-typed language. When you have to deal with external sources and boundaries in any language, you don't have type safety to support you. You must always sanitise your external data. The point of TS and any strongly-typed language is that once you've validated your incoming data at runtime, you can be pretty confident that your data types in your own code are correct.

TypeScript is not strongly typed. It can't be because JavaScript is weakly typed. What TypeScript brings is static typing, which is different than strong typing, though often they are casually used interchangeably, but in the comment you're responding to the distinction is important.

I don't have time to write up full examples for both but I highly recommend looking into it.

Thread Thread
 
jackmellis profile image
Jack

Fair point. Although I think this doesn't really affect my actual point: Whether it's a statically-typed or a strong-typed language, you must sanitise incoming data at runtime, and then you can trust your static typing from then on.

This isn't something that only typescript has to deal with.

As an aside - of course, with typescript you can at any point just go "I don't care about what type this thing is" which means you lose that trust - but this is why you should avoid any or at least follow it up immediately with some form of type guards.

Thread Thread
 
latobibor profile image
András Tóth • Edited

In my own "teachings" I say as and any should only be used with external sources: either a shitty library lacking typing definitions or not knowing how to handle generics or data not yet sanitized.
When you shortcut and in fact "lie" to the type system you are setting up a bug basically.

Collapse
 
joelbonetr profile image
JoelBonetR 🥇

Aren't you able to read the function implementation where should be some kind of documentation about which args it needs and which output it throws?

Something like:

/*
* The includes() method determines whether an array includes a certain value among its entries, returning 
*  true or false as appropriate.
* Parameters: searchElement (The value to search for), fromIndex (Optional; The position in this array at 
* which to begin searching for searchElement).
*
*Note: When comparing strings and characters, includes() is case-sensitive.
*
* Return value: Boolean
*/

"Self documenting code" without typing any documentation like this is even worse than the lack of strong static typing on big projects.

Thread Thread
 
jackmellis profile image
Jack

I'd argue that this adds extra maintenance as you have to ensure the documentation matches up to the implementation. There's no way to enforce the two to stay in sync.

At least with something like typescript you can't change the implementation without the types being updated/corrected.

This is kind of the whole point of self-documenting code regardless of typescript. With comments you have to remember and be responsible for updating the comments whenever you change any kind of implementation detail. It'd only take a quick hotfix or two developers working on different features, and the comments can so easily become outdated.

This of course is assuming that your third party javascript libraries even bother to write jsdocs for their functions. If you use a library with no jsdocs and no ts definitions, you're forced to refer back to the actual documentation, and no dev worth their salt ever actually reads the docs right? 😂

Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇

I can agree and disagree with some points. Reading the documentation makes your work more efficient and reliable. You can use multiple functions you entire life without even knowing they have optional params that can save you some good time, i've seen that many times hahaha

Thread Thread
 
agritheory profile image
Tyler Matteson

Overall this is a fascinating debate that probably doesn't have a 'right' answer but I wanted to add to this 'write docs or don't' point. Writing documentation helps me clarify that I've built what I wanted to design. Sometimes I do it first as a rubber duck exercise and I always gain something from it when I do.

Collapse
 
stojakovic99 profile image
Nikola Stojaković

Exactly because of that. TypeScript will only check types at compile time and only types that are available. Any network calls, system libraries, platform-specific APIs and non-typed third-party libraries have no way of communicating with TypeScript. As you get used to having your types checked and not having to fully understand the code and the platform, errors and bugs will manifest themselves.

And who ever said that TypeScript solves this? No one ever said that TypeScript could be used as a static typed language (like Java or C#) but for writing large JavaScript projects. TypeScript gives you the tools to better describe your entities in the code base or shorter said, self-document your code. When you turn on strict mode and use strong enough code standard (like AirBnB), you'll catch large number of potential pitfalls.

Regarding the third party checks, there are various libraries which allow you to do this, like class-validator. With them, you can do the check on the input data of your applications.

With JS, you make no assumptions about types, and you check the concrete value of the variable to make sure it is what you expect it to be.

And that's exactly the problem which makes all dynamic languages bad for large projects. It's been empirically proven that large projects benefit from using types.

link.springer.com/article/10.1007/...

You can combine the two ways, but what is the point then? If you will spend time writing definitions and then spend time writing code to ensure these definitions are maintained during runtime, why have them in the first place? You can do the same in JS defining your type-checks and the result will be the same but clearer.

How would you do it in JS? Checking type of each construct at each step? As I said, you already have validation libraries, which, combined with TS, can help you to remove most of the possible pitfalls.

I won't comment the second point because it's subjective. I find TypeScript pretty readable.

TypeScript is said to solve JavaScript’s problems. But it does not. Dynamic typing was never a problem in JavaScript, but many other gotchas such as NaN === NaN being false, semicolons being optional or not optional, a linebreak changing an object definition into a scope, syntactic sugar in place of OOP are indeed problems. TypeScript does nothing to solve them, but introduces yet another standard, further polarizing the JS community.

The sole fact that TypeScript prevents you from doing dumb things like adding numbers and strings (yes, implicit conversion is the devil's work) proves that it in fact solves the problem. The problems you listed could be at least partially solved by imposing restrictions. It's not possible to make a complete solution for these things because we have to maintain backward compatibility with huge number of sites written in the JS which use these quirks.

And yes, dynamic typing is a problem as I said, once you hit certain point in your project. That's the first reason TS was made in the first place.

TypeScript is something that compiles into JavaScript, it cannot be a superset by definition.

TypeScript is a superset because it is JavaScript + various other constructs on top of it's syntax like interfaces, enums, generics etc. Just because it compiles to pure JavaScript doesn't mean it's not a superset.

Regarding number five I don't have anything to say since I'm using both open source and proprietary technologies in my work. I care about getting the job done more (but I prefer open source solutions for various reasons).

Regarding number six, we can agree that just because many people use something doesn't mean it's a good tool. But if so much big open source projects have moved to TS and told that it made their development easier, I'll trust them. Especially because it made mine much easier and less stressful.

As you said it adds transpiling time which is something that you definitely don't want. Most companies choose JS (or PHP or Ruby or...) for being interpreted languages which means you avoid compiling/transpiling every single time and you end up with faster development.

Today you still have to do various building processes whether you're using the TS or not (the Babel you mentioned for example) so it's not that big difference. TS compiler is pretty fast and there is also Deno which runs TS out of the box, without compilation to JS.

If you really feel in need to get strong typing you just need to search "strong typing js babel plugin" and you'll find many approaches that can fit for you or for your project.

It is nowhere near TS which has one of the most advanced type systems out there with support for structural and algebraic types.

Collapse
 
vagrantjin profile image
Vagrant Jin Kazama

TS which has one of the most advanced type systems out there

TS compiler is pretty fast and there is also Deno which runs TS out of the box, without compilation to JS.

And that's exactly the problem which makes all dynamic languages bad for large projects. It's been empirically proven that large projects benefit from using types.

Your answer reads like an ode to complexity. I feel I have to defend the "old" languages.
Complexity justifies the high salaries developers command for their monthly paycheck, rather than good, simple, clean, readable code.

And to further my status as a consultant and heathen, why is JS being used everywhere? If you yourself say static typed languages are superior, why not use a static-typed language, instead of added complexity and overhead to bend the time-space continuum of a dynamically typed language to do the work? Why not use C# or Java on the backend? Why add an order of magnitude more complexity to client side code?

You know the answer. I know the answer. Cleverness.

Thread Thread
 
stojakovic99 profile image
Nikola Stojaković

Your answer reads like an ode to complexity. I feel I have to defend the "old" languages.
Complexity justifies the high salaries developers command for their monthly paycheck, rather than good, simple, clean, readable code.

Your thoughts come from the wrong premise. Types don't add to the complexity that much. Yes, it's more work, but it will be complex as much as your project is complex.

Java is not inherently more complex just because of it being static typed. It's more complex because of it's huge ecosystem and the things you can do with it. Java on it's own is pretty straight forward language. TypeScript too. Types don't change that.

I'm always for the simple, clean and readable code and that's exactly one of the reasons why I prefer TypeScript - because I can clearly see what my method takes as arguments and what it will return. The code is self documenting.

And to further my status as a consultant and heathen, why is JS being used everywhere?

It's not used everywhere. We can easily get that impression if we're working solely on the web or we heard how it can be used for embedded applications, desktop applications and so on. Just because something can be used in many places doesn't mean it should be.

PHP could be used for writing desktop applications too, and how many popular desktop applications you know which are written in it? Compared to that there are some popular desktop applications written in JS but most of them suffer from performance issues when you're trying to deal with more CPU intensive stuff. VS Code is an exception because Microsoft invested heavily in making Electron more performant.

If you yourself say static typed languages are superior, why not use a static-typed language, instead of added complexity and overhead to bend the time-space continuum of a dynamically typed language to do the work? Why not use C# or Java on the backend? Why add an order of magnitude more complexity to client side code?

Because I don't get to choose which language we will use on the project. I'm working as a full stack developer on mostly JS projects which all use TypeScript. If I'm given a chance to choose between TS or JS, I'll choose TS. If I'm given a chance to choose between JS and X language for the back-end, where X is Java, C#, Elixir (which is dynamic typed language by the way) or some other technology interesting to me and suitable for the project, I'll choose X.

So yeah, I would use C# or Java on the back-end if I had chance.

You know the answer. I know the answer. Cleverness.

Nope, just gave you the answer above. It's about business decisions.

Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇

I've something to say in here.

  • Java is complex because it adds so many boilerplate that it makes it hard to read. Kotlin solves some points of that but not all of them as well.

example of java code:

public static String testableHtml( PageData PageData, Boolean IncludeSuiteSetup) {
   PageData foo = new PageData( PageData );
   String a = foo.getName();
   // do stuff

   return  a;
}

How this can be more readable?

/* @ params
* PageData, Boolean
* return String
*/
public static testableHtml ( PageData, IncludeSuiteSetup ) {
    foo = new PageData( pageData);
    Sring a = foo.getName();
   // doStuff;
  
   return a;
}

It's a simple example where not so bloatware is added but imagine that on a really big project, having to read the types all the time of you try to figure out what the code does. if you equal a var to a given type, it's inherent that it will take this type.

TS does a better job than Java in this point, for example.

PHP could be used for writing desktop applications too,

When I was a young dev there was a framework for doing that. Of course it embedded an Apache server (I guess) that were virtualised inside this environment to reach that. It was slow because the current tech didn't exists.

PHP like any other interpreted language nowadays is compiled when interpreted for the first time so the server can read the compiled version to run faster. Same happens with JS or Ruby to say some. It also wasted resources to raise this "VM" environment on a time where resources were more limited than nowadays.

Each language has 1 or more runtime environments and PHP as desktop APP have some throwbacks for it not being recommended.

JavaScript by the other hand has to consume notably less resources to run and has an advantage for the implicit way it runs, which leads to more efficiency than PHP (we can enter in more detail about that whenever you want).

... I'm working as a full stack developer on mostly JS projects which all use TypeScript. If I'm given a chance to choose between TS or JS, I'll choose TS. If I'm given a chance to choose between JS and X language for the back-end, where X is Java, C#, Elixir (which is dynamic typed language by the way) or some other technology interesting to me and suitable for the project, I'll choose X.

As I've said before TS is good but using always TS is usually a lack of previous analysis of what you really need. There's no tech to rule them all and all of them cover some needs.
If you are going to make a whatsapp knock-off or audio stream such spotify, you can use Java to deal with this Async operations, which will be a pain in the ass compared to using JS over Node, the dev time will increase notably and the end result will not differ much from one implementation to another, so there's no reason for not using JS on that (to say something).

As second example (and the last to not extend this comment more) would be using TS on a simple Node API that's a CRUD for -let's ssay- email and password of the user profile.

You'll end up with 50-70 lines of code as much, they will be listeners to some route with some resolver in it, well structured. There's no real need or concern that leads you to use TS here. The same way not all things have to be OOP.

Again, analysis part is one of the most important things when starting a project or a new feature. Then having your code to work is half the job while cleaning your code is the other half.

Stay save and code tests,

best regards :)

Thread Thread
 
stojakovic99 profile image
Nikola Stojaković

Java is complex because it adds so many boilerplate that it makes it hard to read. Kotlin solves some points of that but not all of them as well.

Again, this is subjective opinion. Just because there is more to read doesn't mean it's inherently harder to read - you just have more information, but I only see this as a plus because there is no place for ambiguity compared to reading JS (except if you're writing JSDoc, which is less ideal solution than having types where declarations are).

You ask how this can be more readable - it's pretty easy to read for me. Right away I see it's a static method which returns string and takes too parameters, one which is an instance of the PageData and other which is a boolean. I don't understand what's so unreadable here.

It's a simple example where not so bloatware is added but imagine that on a really big project, having to read the types all the time of you try to figure out what the code does. if you equal a var to a given type, it's inherent that it will take this type.

You don't have to spend all your time reading types. Java also introduced var some time ago so you don't have to write huge lines anymore. Most of the types you'll work with will be straightforward, except if you're working on something more complex, in which case it would be of even bigger help to have types in the first place.

JavaScript by the other hand has to consume notably less resources to run and has an advantage for the implicit way it runs, which leads to more efficiency than PHP (we can enter in more detail about that whenever you want).

I agree, but the fact stays that it's not good for CPU intensive tasks (except if you're using some multi threaded environment which are rare - Electron uses V8).

As I've said before TS is good but using always TS is usually a lack of previous analysis of what you really need. There's no tech to rule them all and all of them cover some needs.
If you are going to make a whatsapp knock-off or audio stream such spotify, you can use Java to deal with this Async operations, which will be a pain in the ass compared to using JS over Node, the dev time will increase notably and the end result will not differ much from one implementation to another, so there's no reason for not using JS on that (to say something).

If I need to use JS, I don't need any specific analysis for TS because TS is JS after the compilation step kicks in. JS with much less headaches in every sense. There is no one technology to rule them all, but when I see that JS is suitable, even if I'm going to write a small CRUD app with few routes. It's because TS gives me so many benefits over using purely JS and I mentioned these benefits before. Why would I make my life harder if I don't have to?

If you are going to make a whatsapp knock-off or audio stream such spotify, you can use Java to deal with this Async operations, which will be a pain in the ass compared to using JS over Node, the dev time will increase notably and the end result will not differ much from one implementation to another, so there's no reason for not using JS on that (to say something).

It doesn't have to be pain in the a** if you know what you're doing. There is Akka. If you need to do CPU intensive stuff on top of dealing with async operations it makes more sense to use Java. If you don't and your developers know JS better, it makes more sense to use Node. There are many questions you have to answer before choosing a technology and there are reasons not to use JS even if you're doing async stuff - if it wasn't the case no one would use Go, Elixir, Erlang and other languages for that purpose.

Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇
Again, this is subjective opinion. Just because there is more to read doesn't mean it's inherently harder to read

Yes it is, and it's nothing new, in times of Aristotle they already studied how the way to spell/write things down can change the perception and the attention of the people.
If you say/write something concisely, using the context people will bring more attention but if you add repetition and don't use the context people simply stop paying attention to your speech or text.

This, in programming languages (remember that it's just a language, not to communicate between people but to communicate with a machine, even that, who had to read this language are other people as well) is translate as which we know as boilerplate.

the java syntax (unless you use var, ok) is repetitive and doesn't make use of conversational context.

String a = "foo";
String b = a;

you need to declare the type on the second one even being a copy of the first.

let's set an example in prose:


The women were in the blue house at the top of the mountain, waiting for the sunset.
The blue house at the top of the mountain was being stalked by an strange creature, but the women feel safe inside the blue house at the top of the mountain.

It's detailed, of course but it's hard to keep your attention to this and remember all the stuff you are reading, because people have context, and we're animals that like other animals, want to reach a given situation as fast or efficient as possible, so we like to read like this:


The women were in the blue house at the top of the mountain, waiting for the sunset.
The house was being stalked by an strange creature, but they feel safe inside the house.

Knowing what is easier to read it's a scientific fact and not an opinion.


If you need to do CPU intensive stuff on top of dealing with async operations it makes more sense to use Java. If you don't and your developers know JS better, it makes more sense to use Node. There are many questions you have to answer before choosing a technology and there are reasons not to use JS even if you're doing async stuff - if it wasn't the case no one would use Go, Elixir, Erlang and other languages for that purpose.

You can simply set a Node server to handle requests and resolve CPU intensive tasks specifically inside Python or Java or... APIs/web services.
You can benefit of faster development production and good performance as well. Having devs knowing a specific tech is an important part of the decision but never should be the most important part.

It's cheaper to pay a course to your devs and develop with the right current stack than using a wrong one because is "what they already know". Also devs usually like to learn new things so they'll feel like they are learning on it's current job and will probably be more excited about starting on a greenfield with a new tech.


If I need to use JS, I don't need any specific analysis for TS because TS is JS after the compilation step kicks in. JS with much less headaches in every sense. There is no one technology to rule them all, but when I see that JS is suitable, even if I'm going to write a small CRUD app with few routes. It's because TS gives me so many benefits over using purely JS and I mentioned these benefits before. Why would I make my life harder if I don't have to?

Here I let you a simple get and put verbs from an hypothetical API (there's a nonsense on adding the rest of the verbs because it will be a repetition of those actions mostly) with dummy data.

Do the exercise and translate this into TS and show which benefits can you get from that:

const Joi = require('joi');
const express = require('express');
const app = express();

const courses = [
    { id: 1, name: 'First Course 1' },
    { id: 2, name: 'Second Course 2' },
    { id: 3, name: 'Third Course 3' },
];

app.get('/api/courses', (req, res) => {
    res.send(courses);
});

app.put('/api/courses/:id', (req, res) => {
    const course = courseExists(req.params.id);
    if (!course) return res.status(404).send('The course with the given ID was not found');
    
    const { error } = validateCourse(req.body);

    if (error) {
        let errorMessage = '';
        error.details.forEach( err => {
            errorMessage += err.message
        });
        return res.status(400).send( errorMessage );
    }

    course.name = req.body.name;
    res.send(course);
});

function validateCourse(course) {
    const schema = Joi.object({
        name: Joi.string().min(3).required()
    });
    return schema.validate(course);
}

function courseExists( id ) {
    const course = courses.find( c => c.id === parseInt(id) );
    return course;
}

const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}...`));
Thread Thread
 
stojakovic99 profile image
Nikola Stojaković

If you say/write something concisely, using the context people will bring more attention but if you add repetition and don't use the context people simply stop paying attention to your speech or text.

Can you show me exactly where is this repetition you're talking about? Because declaring something as a String and writing down the string precisely character by character later is not a repetition. Declaring a type and defining a value is not the same, and as I said, type inference is available in Java today, so there are even less reasons to talk about some repetition, especially when it makes code clearer to understand. When you write something like this;

const processQueue = ({ queue }) => {
  // do something with the queue
}
Enter fullscreen mode Exit fullscreen mode

How do you know what's the queue? What it contains? What methods you can call on it? It's easy to read but it doesn't give you any information. Not to mention that you need to define type so that compiler can know what will that variable contain if you're not passing value immediately. Compiler can't predict what you're going to put in it.

This, in programming languages (remember that it's just a language, not to communicate between people but to communicate with a machine, even that, who had to read this language are other people as well) is translate as which we know as boilerplate.

Actually, programming languages we use today were developed so people can better communicate between themselves about what the program does. If that wasn't the case we would still use Assembly or other lower level languages.

Remember what Harold Abelson said;

Programs must be written for people to read, and only incidentally for machines to execute.
Enter fullscreen mode Exit fullscreen mode

It's detailed, of course but it's hard to keep your attention to this and remember all the stuff you are reading, because people have context, and we're animals that like other animals, want to reach a given situation as fast or efficient as possible, so we like to read like this:

Except our jobs as a software engineers is not to look at things from the animalistic perspective but rationally.

It's the empiric fact that types make development easier by describing the possible way some data can be processed. Yes, you write more code, but it's an investment for the future. Next time I come to the part which was self-documented by using types I'll have much less troubles understanding what has to be done.

Having to spend a bit more time to read it is a trade-off which you have to pay for more thorough explanation, but that will remove ambiguity and possible problems in the future stemming from that. Slower is faster.

Knowing what is easier to read it's a scientific fact and not an opinion.

And as I already said - harder to read != more complex.

You can simply set a Node server to handle requests and resolve CPU intensive tasks specifically inside Python or Java or... APIs/web services.
You can benefit of faster development production and good performance as well. Having devs knowing a specific tech is an important part of the decision but never should be the most important part.

It's cheaper to pay a course to your devs and develop with the right current stack than using a wrong one because is "what they already know". Also devs usually like to learn new things so they'll feel like they are learning on it's current job and will probably be more excited about starting on a greenfield with a new tech.

Okay, now we're getting into nitty gritty details and I think you're not really getting me right, so let's put things straight.

I never said that some technology should be used just because developers already know it. It's one of the points you use to choose technology - as I said, there are many points you have to discuss. If we all know JS and JS is not the right thing to use, we won't use it. In your post, you made it look like JS is the only choice for doing async stuff - it isn't, nor it's the best one. It's just that, a choice. Whether someone will use it or not depends on many other factors as well. You can't ignore the fact that market also dictates the choice of technologies, otherwise many of them would never even be chosen anymore for the new projects.

Here I let you a simple get and put verbs from an hypothetical API (there's a nonsense on adding the rest of the verbs because it will be a repetition of those actions mostly) with dummy data.

Do the exercise and translate this into TS and show which benefits can you get from that:

const Joi = require('joi');
const express = require('express');
const app = express();

interface Course {
  id: number;
  name: string;
}

const courses: Course[] = [
    { id: 1, name: 'First Course 1' },
    { id: 2, name: 'Second Course 2' },
    { id: 3, name: 'Third Course 3' },
];

app.get('/api/courses', (req, res) => {
    res.send(courses);
});

app.put('/api/courses/:id', (req, res) => {
    const course = courseExists(req.params.id);
    if (!course) return res.status(404).send('The course with the given ID was not found');

    const { error } = validateCourse(req.body);

    if (error) {
        let errorMessage = '';
        error.details.forEach( err => {
            errorMessage += err.message
        });
        return res.status(400).send( errorMessage );
    }

    course.name = req.body.name;
    res.send(course);
});

function validateCourse(course: Course) {
    const schema = Joi.object({
        name: Joi.string().min(3).required()
    });
    return schema.validate(course);
}

function courseExists(id: number): Course {
    const course = courses.find( c => c.id === parseInt(id) );
    return course;
}

const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}...`));
Enter fullscreen mode Exit fullscreen mode

I get multiple benefits;

  • Right away I see what parameters my method takes and what it will return
  • I won't be able to accidentally pass a course with the wrong structure (you may say it's really hard for this to happen because I'm just changing a single array, but there is still a possibility so - no need to risk)
  • I get better help from IntelliSense
  • Code is more ready for the future if I want to make the project bigger. I can just move interfaces to their own files and keep all the benefits I mentioned above.
Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

now that's a well defined answer where you are right on everything not because you wanted to explain it since the beginning but just why I told you things that were inexact or "falsy" so you want to put the things straight like they are.

That is the kind of explanations that most people need because If it was true that I knew nothing about that and I were talking serious in my sentences, now I could understand what's going on there, even if it's a little bit.

That's the main purpose of this circus and in most cases it's not people not knowing things, it's that people (like you and myself) write down things without really analysing or going in detail, or finding which details are needed to fully understand the topic. Which is normal because we take for granted things that we already know.

I truly believe that if we can answer in comments or explain in posts the things like we do when we're pissed, newcomers could inherit this knowledge, connect the dots and maybe, some day -hopefully sooner than later- became better than us.

I've three more things to say:

  1. Thanks you.
  2. Sorry for making you loose some time.
  3. You can be a good speaker/teacher/writer on this subjects when you want.
Thread Thread
 
stojakovic99 profile image
Nikola Stojaković

No worries. It was indeed an interesting exchange of thoughts. All the best!

Collapse
 
romeerez profile image
Roman K

Let me disagree on "typescript is for large projects": the thing is once the project turns into "large" - it's too late for TS. I've been on various large JS projects, and all people prayed and talked like "let's switch to TS", "soon we will do it". But that's never happened - too much time and effort to migrate. Just imagine a complex js file with a lot of untyped variables, and you have to write types without having any idea of what's happening here - it's too hard.

Thread Thread
 
stojakovic99 profile image
Nikola Stojaković

Of course, I was thinking about projects which tend to become large (although you can't predict that easily - I use it for every JS project I'm starting out these days).

Collapse
 
joelbonetr profile image
JoelBonetR 🥇

Now that's what I expect to read from someone!

Those are the good points to consider about TS!
Even you adding more importance to strong typing that it would had on a good and tested software -regardless of the size- I'll explain myself.

we know that in a perfect world we would probably use TDD, trust our tests at the top of out structure, commit little chunks of code, add proper documentation (not only from devs, but also the features should be documented out of the software on a structured manner) and all IT roles in the project are covered by the best individuals on the industry and so on or we can even fantasise that there's a machine that codes. If we reach this situation for any reason, strong typing would never be a need, because you understand the software you work in and knows how it works, and even when facing a human error, there will be trust-able tests that points us in the right direction.

The need of adding strong typing raises to the moon when we have junior devs, rushing bosses, bad company culture and so on.

Apart from that, for a given piece of software you can discern how big it will be, you always can connect different software made with different technologies without issues so as long as it's decoupled enough and well scoped in it's tasks it will be fine either way.

If you need (need is the keyword here) strong typing, you should be working on something that implicitly needs it for any reason or something bad is happening in your development process. Knowing the cause of this need could be a game changer for you and your teammates.

Arguing that you want it "just in case" is also fine, why not?

You can add TS then if you want mix it with JS if you need it so it will be a good.

Then if we talk about performance, statically typed languages have better performance at run-time intrinsically due to not needing to check types dynamically while executing (it checks before running). Similarly, compiled languages are faster at run time as the code has already been translated instead of needing to “interpret”/translate it on the fly.

TS compiles to JS so there is no issue here on performance, it will -hopefully- be the same than using plain JS.

Thread Thread
 
stojakovic99 profile image
Nikola Stojaković

Those are the good points to consider about TS!
Even you adding more importance to strong typing that it would had on a good and tested software -regardless of the size- I'll explain myself.

Nope - in fact, if you look at my profile, you'll see that I left comment before in one thread where I mentioned the importance of testing. I never said that static types are more important than testing nor that they're sufficient.

I add the importance on static typing because it's been proven over and over that static typed programming languages are better for large scale projects.

strong typing would never be a need, because you understand the software you work in and knows how it works

It would be a need even in that case because humans are not perfect - even with the properly written tests it would be possible to make bunch of mistakes and to pass data of wrong types. Static typing prevents you from making dumb mistakes in the first place.

The need of adding strong typing raises to the moon when we have junior devs, rushing bosses, bad company culture and so on.

No, the need of adding strong typing exists because it has been shown that large scale project written in dynamic typed languages are much harder to maintain. That's one of the reason why TS even came to existence - Microsoft had huge JS code bases and saw how unmaintainable they become after some time (and I'm pretty sure Microsoft engineers do write tests and documentaion).

Types allow you to describe the data and relationship between different data. This allows you to much better predict possible pitfalls (for example, to check if your switch case incorporates all posible cases like Rust does) and so on.

What you're basically saying is that all these static typed languages in the existence today came to be just because there were some cranky bosses and junior devs who couldn't program in dynamic typed lanugages, which couldn't be further from the truth.

Apart from that, for a given piece of software you can discern how big it will be, you always can connect different software made with different technologies without issues so as long as it's decoupled enough and well scoped in it's tasks it will be fine either way.

You can't easily predict how big some software will be. Also, decoupling is a hard process. I know this because I have worked on many microservice based architectures. One bad step and it's easy to make a huge number of errors.

If you need (need is the keyword here) strong typing, you should be working on something that implicitly needs it for any reason or something bad is happening in your development process. Knowing the cause of this need could be a game changer for you and your teammates.

It makes work much easier in the long run. That alone is one of the reasons why I prefer it over the dynamic typing. Sure, that doesn't mean I don't use dynamic typed languages at all - I have a game which is written in Ruby for example.

Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇

Thanks for this kind of comments Nikola, in this discussion I'm playing the role of devil's lawyer but I know those things, I have a career since long time ago. In this platform sometimes I get frustrated because there are many people blind-following things and not even analysing what they should do. Explanations like yours, mines sometimes and other few should get more visibility.

I'll try to pick some time in few days and extract excerpts about all this post in a manner of question/concern -> answer, trying to add external sources for further information and so on for those who want to get more than a surface knowledge and understand the concepts.

In the meantime I'll try to counter some points of view to see how people argue it's opinions or experiences and let's see what can we learn about all those chunks of text! :)

I'll mention you all when this job is done

Collapse
 
chasm profile image
Charles F. Munat

ROTFL. You could use this post in logic textbooks as the epitome of the straw man fallacy: en.wikipedia.org/wiki/Straw_man

  1. TypeScript does not pretend to solve problems with runtime types. Please show where in the official docs it makes that claim? With or without TS, that is the developer's problem to solve. So let's just cross that nonsense out.

  2. TypeScript is optional. You can use as much or as little as you want. If your types are gibberish, you probably just haven't learned to use types well. Anyone who wants to be considered a serious programmer should understand static types, whether in TS or not. It's no different than not understanding how variables work, or scope. Let's cross that one out, too.

  3. This is actually restating #1, but nowhere in the TypeScript docs does it claim to "solve" the problem (which "problem" is that?). TS makes it easier to find type errors at compile time, and helps IDEs to provide better help. End of story. The rest is straw man. Into the loo with this one, too.

  4. TypeScript is a superset because it includes language that is not in JS. What precisely in JS does it prevent you from using? Remember that all TS is removed at compile time and that TS is optional. What nonsense! Maybe take a class in set theory? Consign this one to the trash.

  5. TypeScript is as open-source as React is. As many other major libraries and frameworks are. Angular? What, exactly, is the point here? Don't like M$, don't use it. Really grasping at straws here. From here on it's mostly just filler, no?

  6. That big companies use it means it will be around for a long time, therefore it's a safe bet. And the increasing (skyrocketing, really) popularity of TS means that anyone wanting to work in an enterprise environment will probably need to know it. Sounds like a good reason to learn it to me. It's why I did. So this one is still more BS.

  7. Static types are a feature. JS doesn't have them. Shitcan this one.

  8. This is the only argument with even a modicum of truth in it. But while there is definitely a "TypeScipt Tax", that is true for learning any new thing. That said, learning a type system makes a programmer better at programming. It really should be a sine qua non (look it up). And better programmers write better code.

Just as fixing ESLint errors also takes time, but makes both better code and better programmers. Just as learning new language features takes time, but makes both better code and better programmers.

Wait, what was your point? I think this one's for the bin, too.

And that makes your batting average, um, 0.000.

I'm not a huge fan of TypeScript. as I've said many times elsewhere, I'd like to see the TC-39 committee get off their butts and approve an optional, Hindley-Milner type system with inferencing for ECMAScript. It is long since overdue.

But I can read the writing on the wall, and JS devs who refuse to learn TS will soon find themselves cranks, kooks, and dinosaurs. Whether you approve or not is irrelevant. Read 'em and weep.

Collapse
 
joelbonetr profile image
JoelBonetR 🥇

i know there's much text in the thread and obviously you didn't read it all, which is ok, no problem.

This talk about using or not using TS is just an experiment with the OP and I . I suspected that I would get more explanations if I proposed closed statements that I would find online, slightly modified and that's all, we also use TS as well as JS, that's not the point, not really.

You -unlike the half of the comments and like the other half as well- have the error of stating your pov instead explaining why some assumptions are wrong "as is".

None of what I said is wrong, but also it's not 100% true, that's why it caused so many replies, some for, some against.

The other error you stated is that TS didn't came to solve anything. Obviously this is a silly argument, every tech came to solve a problem, otherwise it would be ignored, there's no reason for anyone to learn something new if it does not solve a real life concern.
Prototype inheritance, Equality and type juggling, Management of modules, Scope, Lack of types and lack of robust OOP system, were the things they tried to solve with TS. Some are solved and working pretty well in JS since time ago, others are not included -yet- and that's why we are still using TS.
If tomorrow a new JS version adds all TS features, in less than 2 years there will not be a single project started with TS and having TS will become a proof that it's a legacy project. But for the moment it isn't like that so, we've to use TS where it's needed.

TS adds syntactic sugar that facilitate us to work with types and other stuff, but at the end you can do exactly the same using JS type checks and custom types if you want. Obviously it will cost much more dev time but you'll end up with typechecks on runtime as well.

People uses TS instead self-implementing this stuff because it makes it easier and faster to go hands on and because having a compiler taking care of this is easier and adds less boilerplate than doing it with vanilla js at this point.

The rest of your answer... I would like you to explain it in more detail because I think you can do it and I plan to write a post with excerpts of this conversations (mentioning each author) from the engineering point of view, concluding about real concerns about one or another. We both know we'll end up concluding that TS is necessary but the questions are: why is it? when is it? and so on.

Collapse
 
jwp profile image
John Peters • Edited

Js still doesn't have classes? Wrong.

TypeScript is a superset or what used to be called a 3rd generation Language. Any thing that compiles down to something else can do everything the base Language does plus all it does. It the same thing as coding decorators.

Best of all TypeScript irritates die hard TypeScript haters.

Collapse
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

classes were not available in 2012's JS, edited adding "att this time" just after to ensure it can't be misunderstood :D

Thread Thread
 
jwp profile image
John Peters

Right, and it took Javascript over 5 years to get the Class

Thread Thread
 
akashshyam profile image
Akash Shyam

lol 😂😂😂

Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

over 5 years? It took like 20 years since JS's first release date 😂😂😂
But it has Objects before that if you want to code using OOP paradigm, we did it and I thing both you John and I can confirm that, it was not funny at all but hey! 😂

I'm not being a hater, I'm playing the devil role at this point to bring objectiveness, I've projects with both JS only and TS but this is not important for this discussion. The real question is what can TS bring that JS can't.

Thread Thread
 
jwp profile image
John Peters • Edited

I never called you a TypeScript hater, but they lurk in every place I've worked.

It took Javascript around 5 years after TypeScript was introduced to catch up.

Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

hahaha I need to clarify just in case. John, you have more experience than me, the only thing that I can think of TS can bring is compile checks, (which is irrelevant on a non-compiled language btw) and the things it implies such putting the intellisense on steroids and things related to domain modeling and domain-driven design which can benefit of this strong typing -which you can get from any vanilla JS babel plugin obviously-

there's even runtime type checkers if you search on google

do you mind any thing that makes me thing that TS is a superset instead a subset? :DDDDD

and yes it took near 5 years after TS release date but we are now in 2021 not in 2012 nor in 2016, so we're discussing the current state

Collapse
 
ashoutinthevoid profile image
Full Name

I'm a terrible phone typist, so bear with me.

With JS, you make no assumptions about types, and you check the concrete value of the variable to make sure it is what you expect it to be. Or, if you do not care about its type in this particular case, you do not. In TS, you rely on the compiler to do it for you.

This isn't a problem with JS or TS, it's a developer choice. If a developer is choosing to blindly trust data, a static type checker is not going to save them from the self immolation they've choosen.

The aesthetic appeal I can partially agree with; plain JS is cleaner in an aesthetic sense. However, in my opinion the various typing options (ts/flow/etc) encode additional information. How one uses the type system dictates how useful that is. Again, blame the dev, not the tools.

It does not solve the problem

I don't think you've been clear on what you belive the problem is or was, and nothing in your examples suggests to me that we have the same idea on what problems static type checking might solve. (Optional semicolons seems a particularly bizarre inclusion. I'm genuinely curious who deems this a problem and why it's being related to types, not style).

It is not a superset...

Other commenters have already addressed precisely why it is.

5-7 I have nothing to say. If those things are important to someone, cool.

As you said it adds transpiling time which is something that you definitely don't want

I can't recall the last time I wrote JS without transpiling it. Using TS feels the same in this respect. If you're in an environment where nothing is being transpiled, minified, bundled, or otherwise built....I guess that's a genuine win for JS. I just personally haven't been in that situation in nearly a decade (even things like require.js dep management had a build step in 2012 and earlier). Other slowdowns I can't confidently opine on, as it seems very much like an empirical point and I have no data to draw from.

Having types isn't a reason to stop writing tests in strongly typed languages, and it's not a reason to stop writing them with statically checked JS. So i suppose we don't disagree on any testing points.


There are various approaches to specifying and enforcing your contracts. Articles like 'parse dont validate' or any of Giulio Canti's posts on dev explain better than I could how one can benefit from using a type system. I think one would be wrong to dismiss TS for the reasons you've offered.

On the other hand, most of the real world TS fans I've met in person fit this group:

TypeScript began its life as an attempt to bring traditional object-oriented types to JavaScript so that the programmers at Microsoft could bring traditional object-oriented programs to the web.

Taken from TS' docs. TS made it easier for them to avoid learning actual JS, and they found that very exciting. I found the results rather horrifying, but ymmv. As others have said, at this point they can use JS syntactic sugar to practice OOP as a religious dogma instead of applying it thoughtfully when appropriate to the problem.

Ultimately, how you use the tools determines the value you receive.

Collapse
 
joelbonetr profile image
JoelBonetR 🥇

Very good contribution, concise and well explained, I genuinely coincide in some points with you.

Collapse
 
latobibor profile image
András Tóth

I will write about "Toxic flexibility" soon. The fact that I can do this in JS:

var foo = {
 doMagic() {
   console.log(this.somethingNotYetDefined + ['55'])
 }
}

bar.somethingNotYetDefined = 123;
bar.doMagic();
Enter fullscreen mode Exit fullscreen mode

can be great when your project is 1 file under 200 lines, but not when you have multiple developers working on hundreds of files. This level of flexibility means that you cannot trust any line of code, you have to read every line of every function you call and even then there might be somewhere some code that for fits and giggles change the very object you trust.

Not to mention the living documentation part of having types of parameters and return types. A smart engineer will know how to communicate with those. I have also found that it makes you write simpler code: having functions where clear inputs create clear outputs. Things that are impossible to type tend to be the ones having the most esoteric bugs and edge cases.

Collapse
 
joelbonetr profile image
JoelBonetR 🥇

the language lets you do that, but if you do that... well.

I also can make a calculator App and do something like:

function sum(num1, num2) {
    return num1.toString() + num2;
}

if you do stupid things that are or can become unpredictable, don't blame the language

Thread Thread
 
latobibor profile image
András Tóth

I get your point, but there's one entirely other aspect than fellow engineers: IDEs. IDEs do not know if you are a bad engineer or a good one. Therefore they have to treat every line of code as I wrote above: with the chance of it horribly mutating.

The whole reason about Typescript if you read the interviews was give better tooling. When you opt-out of it you opt-out of better tooling.

The irony is that even for hardcore, ultra conservative JS developers the advantages of TS is seeping in: if the package you use have typings your IDE would be able to use that info for code completion.

Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇

Another good contribution to the discussion, this is converting into a gold mine, thanks András

Thread Thread
 
latobibor profile image
András Tóth

dev.to/latobibor/toxic-flexibility...
As I promised, here is the article.

Collapse
 
bcowley1220 profile image
Brendan Cowley

Very well thought out. I am in the dissension camp also. Extra layers of complexity and code and quite frankly makes things way harder than it should be

Collapse
 
maixuanhan profile image
Han Mai

Wow, so many misleadings in your comment. 🤫
Other guys will point them out. I just want to point out the biggest that you claim it hurts the development time.

Do you know that most of the IDEs rely on the typescript to build the autocomplete (based on the type definitions provided along with the libraries? Those type definitions are written using type script) that helps you accelerate your coding speed. Imagine you have to write a SW in notepad 🗒, or even worst, browse some source code in notepad. Well, jsdoc may help but it may deviate from the real implementation. Not cool.

Typescript can be JavaScript but JavaScript cannot be typescript. Who is superset now? 😎

From my own experience, it is much more difficult to maintain a software written in JavaScript than the one written in typescript. Some of my teammates tend to use JavaScript in a typescript project led to unmanageable source code which caused a lot of time to read and debug and enhance.

I bet that you didn’t have enough time working with typescript to have a good experience to leave a more fair comment than that. Hope you will give you another chance to be IN to the typescript. (Actually I don’t care since without you it is still good 😌)

Collapse
 
joelbonetr profile image
JoelBonetR 🥇

I just copied some argues that I've found on internet, applied some typical concerns on top of that and edited the output having a reasonable argument.

None of what I said is wrong, it just depends on many different factors such project structure, architecture, design and so on.

I use TS too, not a hater or something similar, but when you ask people for further/deep explanation they usually skip it, but when you type something that they feel incorrect or counters it's believes, they argue properly.

It was some kinda like an experiment with @akashshyam and we (as you can see) ended up with some good and structured comments from the engineering point of view, which is nice.

BTW using TS is good, but always using it is a lack of analysis of what you really need. It help with different things but there's no warranty that by simply using TS you project will be better structured, more maintainable and so on, it will depend mostly on the implementation.

Knowing the bad parts of TS as well as the good ones can help us all to end up doing a better job, don't you think?

Thread Thread
 
maixuanhan profile image
Han Mai • Edited

What is the point to repeat the opinions commented by other guys? I don't think writing a long comment called a "deep explanation". In fact most of the points in your original comment are subjective and lack of the statistical evidence. And I think you've probably also known that because that kind of comment can be posted as an article itself but it would be low quality since lacking of foundation and yet it was just a comment.

BTW using TS is good, but always using it is a lack of analysis of what you really need. It help with different things but there's no warranty that by simply using TS you project will be better structured, more maintainable and so on, it will depend mostly on the implementation.

Since we are comparing b/w JS and TS, I have to say that using JS costs us extra effort to create a well structured project because it is dynamic. In contrast, TS with its rich support on type things will cost us less.

Knowing the bad parts of TS as well as the good ones can help us all to end up doing a better job, don't you think?

Till now, I find that only the learning curve is the disadvantage of TS (comparing to JS). Some young folks may read your comment and directly say NO to the TS, that why I have to speak out the "misleading" word which is nothing personal. Again, it is my subjective opinion but then those folks will notice the controversial and will look into the topic carefully and finally make a better decision to continue to be IN with TS or not.

Collapse
 
akashshyam profile image
Akash Shyam • Edited

Not anymore. True, when TS was first introduced in 2012, it had features like classes, still not available in JS by this time. But JS had come a long way since then, and now TS is struggling to keep up. If there is anything missing in JS, there is a babel plugin to do it.

Well there a couple of things that I've pointed out which are still not present in javascript. And moreover, javascript has been copying typescript features such as the ? optional chaining operator. Which shows TS features are useful and not overkill.

Collapse
 
joelbonetr profile image
JoelBonetR 🥇

which things can TS bring that JS lacks? please explain or make a list

Thread Thread
 
akashshyam profile image
Akash Shyam

Yeah even I want to know this!

Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇

so If you don't know that why you add this argument? LoL

Thread Thread
 
akashshyam profile image
Akash Shyam

Wait my bad... I thought in reply to the comment it means what extra does JS give that TS does not provide.... because you said so in the previous thread(7 tips for clean code). I've mentioned in the post the extra features TS provides

For example, public, private and protected fields, abstract classes, optional chaining and nullish coalescing(which was copied by JS) etc

Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

if was "copied" by JS is already on JS so let's talk about the others. do you think they can't be implemented using JS?
codepen.io/joelbonetr/pen/xxdYdWb

this is -maybe- a vague approach but I insist that if it can be done in TS it will probably can be done in plain JS (unless it's a strict compile time job)

Also take a look at:
stackoverflow.com/questions/55611/...

But in fact, do you really need this?
JS is used to build components in the frontend (which would be better to keep them as isolated and uncoupled as possible) and APIs in the backend (which are metaphorically also isolated components that handles a specific task).
If you are going to code a monolith run and embrace TS but if you are in microservices then... you can simply use JS.

Neither you need OOP, there's no one paradigm to rule them all, it will depend on the project needs. If you put your preferences over the project needs the result will be worse. It's like a mechanic engineer using always the same engine for all the vehicles he design.

Thread Thread
 
akashshyam profile image
Akash Shyam

If you are going to code a monolith run and embrace TS but if you are in microservices then... you can simply use JS.

Ah for microservices, it will be difficult to keep track of various types of arguments across multiple microservices and it gets tedious to write and read long comments.

Thread Thread
 
miketalbot profile image
Mike Talbot ⭐

Or use JSDoc...

Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

wdy need to track those types of arguments? when you create or consume an API there's a contract (on REST APIs) or a Schema (in GraphQL APIs) so you'll know which kind of data you are retrieving at this exact point.

BTW most of time you don't need to have a specific type.

Imagine you retrieve data from whatever source and you need to print this data inside some node element, something like

/*
* Receives an object with the props
* name
* age
*/
function doStuff(data) {
  return `Hello ${data.name}, we'll send you a cake for your ${data.age} birthday!`;
}

Can you spot any issue for having dynamic typed props here?

Collapse
 
jessekphillips profile image
Jesse Phillips

The NaN != NaN thing has little to do with Javascript and everything to do with implementing a standard:

This is a follow up question to What is the rationale for all comparisons returning false for IEEE754 NaN values? (I think this is better as another question than a comment). It has a very good answer which is missing exactly 1 important thing: why is NaN != NaN?

Collapse
 
seanmclem profile image
Seanmclem

"what's the point" is not the same thing as a "risk"

Collapse
 
dominikbraun profile image
DB

Hats off for posting such a courageous comment on a website full of TypeScript devotees! :-)

Collapse
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

😂 TS has good things as well but as most people use always the same reasons to base it's speech like a mantra, without looking deeper so I want to add a bit of controversy and objective analysis about the current situation, you don't have to trust me anyway, just search for information, do your tests and so on, you may find things that I didn't as well :D

Collapse
 
captainyossarian profile image
yossarian

Regarding: It is messy. If you really looking for unreadable typings you should definitely check my blog catchts.com/deep-pick . This is what I'm calling hard to read

Collapse
 
joelbonetr profile image
JoelBonetR 🥇

thanks for sharing, i'll take a look at it :)

Collapse
 
podarudragos profile image
Podaru Dragos

very cool !

Collapse
 
codingjlu profile image
codingjlu

Are you... Michael Krasnov? Or just a fan/copy-paster? everyday.codes/javascript/7-really...

Collapse
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

It's a copy paste (explained in the thread), long story short, and as a TLDR I'm not against TS, I was playing a "I'm against that" and see how the thread evolves. It contains very good answers! Check them out.

In fact I'm encouraging people on adopting certain practices to deliver better code Like in this post.

I understand why most [Java, C#, ...] devs experience some kind of rejection about non-typed code (I worked 4 years or so with those as well), but From a reallistic point of view the major part of JS devs or JS projects will not jump to TS because the use-case does not provide enough pros for the cons (I'm talking about business software), -you can check how many available open positions ere there in Linkedin for both JS and TS- nor is TS a tech to rule them all, but knowing the pros of it can help when it's necessary or best to use it and what can better be solved with proprtypes, TS-Pragma + JSDoc and so on.

Sooner or later I'll recap all those ideas or statements against or in favour of TS in a single post (It's taking me some time 😅)

Cheers!

Thread Thread
 
codingjlu profile image
codingjlu

Okay. I didn't express any opinion previously, so I'm not sure what you mean exactly when you talk about all that, but now that I have the opportunity: I really don't like TypeScript because first, (okay, I know this is cringy) it's made by Microsoft (no, I don't use VSCode for my serious projects). Besides that, it's a lot of extra code (and time) you have to write, and often it gets very frustrating messing with types and the such. Also it's just annoying to have to go through another compilation stage to run code. People say Typescript is self-documenting when you read it, but to me it's self-destructing. The syntax just complicates everything and I don't often encounter problems with types of anything. If you want self-documenting, just stick with JSDoc, where there's actually documentation. Why, you can just read the comments!

I'm fine with plain JS. TypeScript doesn't seem to offer me substantial benefits, and where the real bugs are, TypeScript would not solve the problem. So, no to TypeScript.

Collapse
 
gitpaulo profile image
Paulo Santos

I'm just throwing this in here: earlbarr.com/publications/typestud...

PS: Very valid points but presented in a poor manner set out to spark debate. Shame really.

Collapse
 
netssrmrz profile image
Esteban Ramirez

very nice to see someone using actual research to make a point. id like to add that ultimately wed need more than a single study to validate the results. but if they hold out, its still not an endorsement of typescript since, as stated in the research, it is only one of the various ways one can add types to javascript. as a long time c# and java developer im very comfortable using types but i dont believe typescript is the answer for javascript.

Collapse
 
netssrmrz profile image
Esteban Ramirez

great reply. 100% agree. you should definitely make it a standalone article.

Collapse
 
jwp profile image
John Peters • Edited

TypeScript drives Javascript standards which lag what TypeScript can do now often by 5 years. That's how slow Javascript really is.

MSFT is one huge player and no slouch on creating compilers and continuously improving the language.

Anders Heljsberg is an industry icon.

TypeScript can easily mix in pure Javascript.

Even Google deemed TypeScript an approved internal language.

All TypeScript becomes Javascript functions anyway giving 100% safety.

Design time intellisense is over the top awesome and a major time-saver.

If a person can speak 2 languages instead of one they have less narrow options.

TypeScript is so similar to C# that moving to web assembly is easy.

The best part about TypeScript is that it irritates Javascript bigots.

Collapse
 
akashshyam profile image
Akash Shyam

Yep, Agree with you completely!

Collapse
 
latobibor profile image
András Tóth • Edited

I don't want to work on vanilla JS projects anymore, because it really wastes my time.

The 2. Extra code part is legit, however I will have my time spent in the multiples when I have auto-completion, when I don't need to check and read code of a function to know what the hell it accepts as a parameter and what the hell will it return and when I do refactoring.

So the tighter the deadline the more I need TypeScript.

Collapse
 
kalashin1 profile image
Kinanee Samson • Edited

TypeScript was created to add super powers to JavaScript. Most people think that TypeScript is just a different way to write JavaScript. No, TypeScript goes beyond that, TypeScript is a tool to build applications for the web.

I bet you pound for pound, learning TypeScript will further increase your abstraction and problem solving skills, with TypeScript you can manage complexity in an organised and structured format without feeling restricted.

Either approach you implement to writing your codes will be upgraded when you write TypeScript, and no matter how much people want to say it's only static typing. Only static typing is the difference between an orchestra and a crazy band.

And If you say extra code is a disadvantage to TypeScript, is it better to write less code that you don't fully understand or is it better to write more code that you do understand? I don't really see extra code as being a disadvantage to TypeScript, plus there's supports type inference coupled with structural typing.

The extra learning curve attached to TypeScript is definitely worth it, the journey you go through when you learn and understand how TypeScript works, will leave off with better understanding about functional and object oriented programming in general and also how you should design applications.

Collapse
 
sysmaya profile image
sysmaya • Edited

Learning a new language by being lazy to learn to use:
isFinite()
isInteger()
isNaN()
isSafeInteger()
parseFloat()
parseInt()
It seems that developers who love TypeScript still don't know that Javascript code can be commented out.
Add comments to your javascript code directly without having to use TypeScript.

/*
This function returns a Number.
This function does not return an array.
This function does not return an Image Canvas.
This function returns the sum of 2 numbers.
This function does not work if you pass photos of numbers
If you find it difficult to use this function, you may want to use TypeScript.
*/
function sum( numberA, numberB ){
   return Number( numberA ) + Number( numberB );
}
Enter fullscreen mode Exit fullscreen mode

Did you know that javascript can store numbers?

var myNumber = Number("23");
Enter fullscreen mode Exit fullscreen mode

Did you know that javascript has a function called typeof?
Did you know that this function tells me what type of data it stores?

if (typeof variable === "number") {
    //...
} else if (typeof variable === "string") {
    //...
} else if (typeof variable === "boolean") {
    //...
} else {
    //...
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
fabd profile image
Fabrice D. • Edited

I just wish they stop adding gazillions of language features to JS and instead add some basic typing. Look at php it has some nice basic typing, it’s super easy to read. We need some basic typi g features in native Javascripts, just "good enough" would go a long mile over no typng at all, and a million times better than the insane levels of abstraction TypeScript creates.

Problem withTS is you’re not just learning TS. This is a fallacy, in fact you have to learn to master TS and you have to learn all the types for any library you use because of course there is always 50 different ways to type your library. Like, try using native dom with TS... you spend so much time figuring out what types in those .d.ts files you should use to do something. None if that is "self documenting"... you have to spend hours looking at other people’s code, and opening the declaration files. You’re really learning an entire layer of abstraction on top of the library you’re using in the first place.

If I used TS only with my own Javascript then we’re looking at an entirely different scenario. In that case I use TS however I want with more or less strict typing, and I don’t need to study how someone else created types.

Have you looked into types for eg. vue 3 ? It’s so over the top abstract imho, and there is no guide anywhere to tell you how to use them. You probably only need 10% of the types declared, since many of these are for the library’s internals... but the types are not sorted out for you (ie. internal utilities vs public consumption of the library). You have to trawl through these files and spend lots of time trial and error.

For me 95% of the worth of TypeScript is just to be able to declare a structure (like good old C structs), declare function params and return types.

Javascript needs a "loose" , "good enough" typing added to the native implementation, that would be much more accessible.

Collapse
 
munkacsimark profile image
Márk Munkácsi

TS is good, I love it. But you can achieve bugproof and readable code with JS as well. I think this depends on the team you work with. When you need to do things asap and work with juniors, you might need a code with strong TS foundation to ensure quality. But if you have proper code reviews and a knowledge-sharing culture with time to discuss architectural decisions and learn from each other, JS should be as good as TS for you.

Collapse
 
kayis profile image
K • Edited

I think, TypeScript really shines in monorepos.

I have code for backend, frontend, and infrastructure in one repository and all is written in TypeScript.

When I send data to the frontend, I can reuse the interfaces defined on the backend.

When I write data while deploying infrastructure, I can use the interfaces defined in my IaC in the backend.

Every time I change one of those interfaces, TypeScript complains if things break.

Collapse
 
stevepryde profile image
Steve Pryde

As someone who has worked in test automation for many years, this is for all the JavaScript Devs out there who want to argue against typescript. TL:DR you're just wrong. Sorry.

Does typescript hurt productivity?

If you're only measuring time until you launch your code over the fence, then sure. But what about the bugs in production?

What about the time taken by other teams or your customers who either have to debug what went wrong (obj is undefined / has no such method) or wait for your fix?
What about debugging time?

Typescript catches type bugs that would otherwise have gone to production.

Are JavaScript Devs more careful because they know they have to check types?

Sorry, but no. As a QA this defense is almost laughable. There may be some careful Devs out there (but still why check things manually when you can have the compiler do it for you?) But in my experience they are few. What is common are Devs who are over confident in their ability to write bug-free code.

Just use typescript. Seriously. You may think JavaScript is just as good at catching type bugs but if you honestly think that, then you need to have a chat with your QA team.

Collapse
 
bennycode profile image
Benny Code

TypeScript is a superset of JavaScript. It has all the functionality that JavaScript offers plus more. The TypeScript compiler also comes with an „allowJs“ option which makes it possible to import plain JavaScript in your TypeScript project. That’s a great starting point if you are tight on schedule. And if you are fighting with TypeScript errors, then this page might help you: typescript.tv/error-ts/