DEV Community

Cover image for To Typescript Or Not To?

To Typescript Or Not To?

Akash Shyam on July 27, 2021

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

Collapse
 
jwp profile image
JWP • 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
 
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
 
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
 
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
 
tlylt profile image
Liu Yongliang

I will pick TypeScript over JavaScript because I think type awareness is pretty important and useful.

I suppose as an individual it’s totally a personal preference. As a decision for the team, we have to judge on a case by case basis. Having done both, I enjoy the developer experience provided by TypeScript more than JS. But you might get the opposite feeling as well, and that’s totally ok. I am just glad that we can all use a tool that we like and still achieve equally impressive outcome.

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/

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
 
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
 
octagon profile image
Mostafa

Well, I used to love typescript as it's static typed so every move inside my code is predictable with typescript ( you knew something from the future ) BUT!!! It's overwhelming when you are using it with react / redux / node / etc.. I found my self downloading extra @types packages for predefined generics, interfaces, etc..and here the red alert of time consuming, ok later i will have the level down and autocomplention features but these features it wasn't for me the cold bottle of water in the dessert.

Collapse
 
karanpratapsingh profile image
Karan Pratap Singh

Nice article, thank you for sharing. Also, ignore the haters!

Collapse
 
efpage profile image
Eckehard

One important argument might be protection of the source code. With Javascript you need to publish your source - even if they are minified or obfuscated (I´m not sure this really helps). And this is an additional step too.

You can surely use code that was transpiled from JS, but I assume it´s not as useful.

Collapse
 
joelbonetr profile image
JoelBonetR 🥇

?? when you use a bundler it just minifies and ofuscates your code, the output for the same code will be almost the same in JS than in TS, there's no point here.

Collapse
 
ifierygod profile image
Goran Kortjie

So... TypeScript is a good?

Collapse
 
joelbonetr profile image
JoelBonetR 🥇

Hahaha yes it is. Even I added the comment about 8 reasons for not using it, it was to add a bit of controversy and none of the things I said are wrong. Even that you should learn TS if it fits into your stack.

If you work with JS or plan to be a JS dev, you should learn TS after learning JS, it may help you in different ways :)

Collapse
 
prod profile image
Arnaud Leymet

Maybe a subtle typo in the post title: I'd have replaced "Or To Not" by "Or Not To" for a more correct grammar 😅

Collapse
 
akashshyam profile image
Akash Shyam

I will edit it immediately. Is this "more correct grammar" correct grammar? Can grammar be defined as "more correct" 😂?

Collapse
 
prod profile image
Arnaud Leymet

:D

Collapse
 
kenethsimon profile image
kennyLFC

I dont know when ill finally learn typescript its so stressfull but i think ill learn when its a must to use

Collapse
 
akashshyam profile image
Akash Shyam

Why do you think it's stressful?