DEV Community

Cover image for TypeScript is a waste of time. Change my mind.

TypeScript is a waste of time. Change my mind.

Better Coding Academy on July 28, 2019

I think that TypeScript is a waste of time. However, with the level of support TypeScript has, I know I'm bound to ruffle a few typed feathers her...
Collapse
 
stereobooster profile image
stereobooster • Edited

UPD: I turned this thread into article dev.to/stereobooster/type-system-f...

Ok let's start constructive conversation by fixing some terminology: JS is typed language, it is dynamically-type-checked language (or some people short it down to dynamically typed). JS has types: string, number, bool etc. JS has type errors (not much, but still)

null.func // Uncaught TypeError: Cannot read property 'func' of null at <anonymous>:1:6
Enter fullscreen mode Exit fullscreen mode

JS has implicit coercion, which may create impression that there are no types in JS. Read more here.

So the question of use or don't use TS boils down to: do you want to do static type checking or not? (Dynamic type checking always there). And there is a trade of: you need to write a bit more code (type annotations) in order to make static type checker work. It's up to you to decide if it worth it or not.

As well, you may be confused by soundness of type system. Some type systems are sound e.g. they can prove there are no type errors. TS is not sound (any type), but you can bulletproof it with tsconfig, by setting all strict checks to true. And by prohibiting usage of explicit any.

However, because TypeScript compiles down into JavaScript, regardless of how carefully designed your types are, there always is the chance that a different value type sneaks into a JavaScript variable.

You can make a bridge between static type system and dynamic type system. Check that type are valid dynamically on the input (which is unknown and uncontrolled) and rely on the static type checker through the rest of the programm

for example:

const makeSureItIsAString = (x: any) => {
    if (typeof x !== "string") throw new TypeError("Not a string")
    return x;
}
const nickname = makeSureItIsAString(userInput())
// we are sure that nickname is a string in this part of the code
Enter fullscreen mode Exit fullscreen mode

read more about io validation here

Collapse
 
bettercodingacademy profile image
Better Coding Academy

Thank you for your input! Allow me to respond and clarify:

JS is typed language, it is dynamically-type-checked language (or some people short it down to dynamically typed).

Yes, I know. However, I wanted to differentiate between TypeScript / Flow-based JavaScript and JavaScript code that doesn't have TypeScript / Flow. I was first going with "plain", but then again, technically you can have JSX and other non-JS features without static types, so that's why I settled with "untyped".

And there is a trade of: you need to write a bit more code (type annotations) in order to make static type checker work. It's up to you to decide if it worth it or not.

Yes, I agree completely. However, I also believe that it is not worth it in the majority of cases, and that many people are misguidedly using TypeScript believing that it will save them time when in fact it only slows down development in both the short and long-term.

TS is not sound (any type), but you can bulletproof it with tsconfig, by setting all strict checks to true. And by prohibiting usage of explicit any.

This is true; however, in my experience this only leads to lots of red squiggly lines. It's impossible to do completely strict types in TypeScript / JavaScript, and there's always going to be that one case that cannot be fixed with this. Before you know it, you've got half-types and hacked code all over the place, and that's something that's not satisfying at all, especially when you've spent an extra 20-40% of development time writing up types, downloading type libraries and exporting interfaces.

You can make a bridge between static type system and dynamic type system. Check that type are valid dynamically on the input (which is unknown and uncontrolled) and rely on the static type checker through the rest of the programm

You sure can, but I would argue that if you want true type safety and security you should look at a statically compiled, more lower-level language. For example, in many large companies the API that interacts with the database is almost always written in a statically typed language such as C++, C#, Java, etc. - I don't think that TypeScript is the solution here. Plus, importing a function makeSureItIsAString seems like overkill just to make TypeScript support complete.

Once again, thank you for your detailed response, and I hope my response has been appropriate!

Collapse
 
cubiclebuddha profile image
Cubicle Buddha • Edited

I’m really disappointed to hear this same subjective phrase again:

when in fact it only slows down development in both the short and long-term.

I was hoping to find some objectivity. At a minimum, can you please try to convince me that TypeScript slows you down more than it speeds you up?

Consider the fact that I wanted to rename a variable yesterday and VSCode let me do it (and it can only do it accurately because of TypeScript). It changed the variable in 78 files. And this is important: it didn’t just do - “find and replace...” it did it intelligently. To refactor a variable name in JS would have taken a very long time and I would have had to regression test the entire codebase to make sure I didn’t break anything. I would estimate that a full regression test of my application would take 1.5 days.

And you also forgot about the fact that TypeScript helps to communicate your meaning to future developers. Isn’t that important?

So if it helps significantly with refactoring and helps you be a better coworker, then why is it a waste of time?

Thread Thread
 
pb8226 profile image
Paul • Edited

Good point, ease of refactoring is a place where static typing helps.

Thread Thread
 
xcs profile image
Cristian • Edited

My experience was the same: I was forced to do numerous refactorings over big codebases, all done by pressing two buttons thanks to TypeScript, refactorings which would otherwise have taken hours with plain JS. TypeScript is a godsend for the JS ecosystem in my opinion.

Thread Thread
 
wmertens profile image
Wout Mertens

Vscode refactors plain js just fine. Typescript does not help with that.

Thread Thread
 
g1itcher profile image
G1itcher

I don't think that's true across multiple files and variables. Especially when multiple classes/interfaces have the same variable names

Thread Thread
 
wmertens profile image
Wout Mertens

Ah - you're renaming a variable in an interface? In that case, yes, probably vscode can do that thanks to typescript, and wouldn't be able to do it without it.

OTOH, all the times I did this, I did a global search&replace, eyeballing to make sure, and having the tests for extra verification.

Thread Thread
 
jsalinas11 profile image
Jordan

Uh, wait why are you using a single variable across 78 files? If I have to understand 78 files to understand a feature it sounds like you have bigger problems.

Thread Thread
 
cubiclebuddha profile image
Cubicle Buddha • Edited

That’s a lot of judgement Jordan. You seem to be making some assumptions.

“uh, wait why are you using a single variable across 78 files? If I have to understand 78 files to understand a feature it sounds like you have bigger problems.”

For a moment, suspend your assumptions and consider the fact that we had a valid reason for updating the the name of a property on some data. The reason the variable change effected 78 files is because we renamed a property on a data object that we use throughout the entire system. And since we have many api tests, end-to-end tests, unit tests, and more it caused a large change. But that’s the beauty of TypeScript... I can make a change that effects the entire system without causing any quality concerns.

So while your assumptions involve a change to one feature, in reality this change effected all features. When you take a functional / data-oriented approach it’s not uncommon to have many transformation functions that manipulate the data. And since I currently work on a data visualization UI, there are a great many ways that the users want the data to be transformed.

Does that clarify how one variable name can ripple out? Hopefully it communicates how TypeScript allows my team to continuously refactor with safety and without having to spend a bunch of time updating tests just because we learned that we originally misspelled a property on the data an API returns.

Thread Thread
 
jsalinas11 profile image
Jordan

Yeah, you're right I did judge. Sorry. I don't know your codebase, I just find it odd that a single variable would exist across 78 files. Feels wrong to me. Something like KISS or maybe SRP come to mind. But again I don't know your codebase.

Thread Thread
 
wmertens profile image
Wout Mertens

I think what they were doing is renaming a key in an interface, like going from data.online to data.isOnline

Thread Thread
 
xcs profile image
Cristian • Edited

Or adding data.timestamp. With TS you automatically get notified of all the places where this data has to be set and also you now automatically know everywhere you use data that it also has a timestamp property. Also, TS ecosystem goes further than that, you could have Protobuf definitions that might be updated because data is serialized and sent over the network to multiple other services, and with the updated TS typings everyone just knows about this change and can update their code accordingly. And yes, this data interface could be used by hundreds of files across multiple services and git repos.

Thread Thread
 
rjmunhoz profile image
Rogério Munhoz (Roz) • Edited

Vscode refactors plain js just fine. Typescript does not help with that.

Actually, I might be mistaken, but VSCode uses tsserver to better understand your code and do stuff like refactoring, IntelliSense and stuff.

TypeScript isn't only able to perform static type checking on explicit types, it also infers types quite well. It's even possible to write plain JS, enable allowJs and checkJs on your tsconfig.json and let it infer and type-check stuff for you.

This also takes me to another point: in my experience I hardly type stuff other than function parameters; typescript can, usually, infer the rest. So arguments like "you write more code" get a bit weaker, IMHO

Thread Thread
 
badsyntaxx profile image
badsyntaxx

I hardly type stuff other than function parameters

This is what I don't get. If you're just gonna mostly do normal js stuff anyway, then whats the point? Shouldn't you just comment your function and describe the expecteds anyway?

This isn't rhetorical nerd snark. I'm really want to know.

Thread Thread
 
xcs profile image
Cristian

One thing to note is that most of the stuff is inferred. So by typing function parameters, almost all data in your app will have an inferred data type (because knowing the parameter types will automatically result in knowing the return types).

Thread Thread
 
sean_mchugh_8d46a2fcaf096 profile image
Sean McHugh

you had the same variable in 78 files!? and you're lecturing us about bad design?

Collapse
 
cubiclebuddha profile image
Cubicle Buddha • Edited

This article has some misinformed opinions being reported as fact. I don’t mean that as an insult, I am just sad that there is no empiricism involved. Allow me to clarify:

For example, in many large companies the API that interacts with the database is almost always written in a statically typed language such as C++, C#, Java, etc.

All of those languages are weakly-typed when it comes to the MOST important aspect:

// valid C#
String myStr = null;

// invalid TypeScript 
const myStr: string = null;
Enter fullscreen mode Exit fullscreen mode

Do you see how big of a problem it is that C# allows reference types to be implicitly nullable? That means that you can never know if your data is there are not. :( But with TypeScript you can have confidence in your code. The only languages that have strict null are TypeScript, Kotlin, and Swift. Can you see now how your subjective statement above is both incorrect and misleading? I feel like it’s the equivalent of “the cool kids are using C#.”

Plus, importing a function makeSureItIsAString seems like overkill just to make TypeScript support complete.

There’s no reason to write functions like makeSureItIsAString when libraries like io-ts do all of that work for you of ensuring type accuracy at compile time AND runtime. So if you’re looking to build an enterprise-grade app, io-ts or tsoa are wondeful tools to eliminate bad data from even getting through the front doors.

Thread Thread
 
stereobooster profile image
stereobooster

Let's use softer tone. Everybody has holes in their knowledge, it is ok as far as person willing to learn and take part in reasonable conversation. (Conversation was pretty reasonable so far. ❤️@parkroolucas. The title is a bit harsh, but I guess this is meant to be clickbait).

All of those languages are weakly-typed when it comes to the MOST important aspect:

Weakly-typed/strongly-typed is ambiguous terms. See here

Thread Thread
 
cubiclebuddha profile image
Cubicle Buddha • Edited

The title is a bit harsh

Yes. How many of these anti-TS articles are there? But when you look at the usage rates, most of the developers who try TS are interested in using it again.

Thread Thread
 
stereobooster profile image
stereobooster

I totally get you ❤️. What I'm saying if we all switch to this tone, it would be hard to have constructive conversation ¯\_(ツ)_/¯ (Yes author used the provocative title and text, yet somebody should stay cold-blooded)

Collapse
 
codemouse92 profile image
Jason C. McDonald • Edited

...in my experience this only leads to lots of red squiggly lines.

I don't know much about TS (and not a fan of JS, but let's leave that out of this), but I do know a lot about both C++ (static typing) and Python (dynamic typing).

If your code is filled with red squiggly lines from any linter or other static analyzer, you can almost certainly depend on your code being the problem, not the analyzer!

The same flawed logic in what I just quoted at the top is the reason C++ developers are afraid to turn on -Werror: "but, but, my code won't compile, it'll just give lots of errors.

I've seen that issue in nearly every language I've worked in, so it simply tells me that if someone is working in TS, and is avoiding strict mode because "too many red squiggly lines," you can bet the house they've been writing bad code. Chances are, in fact, they're using TS as if it were nothing more than JS-with-type-hints-on-top...and utterly eschewing the patterns and logic one must follow when working with types.

All that to say, if someone's gripe is too many red squiggly lines, I wouldn't trust the quality of their code in that language.

Collapse
 
stereobooster profile image
stereobooster • Edited

JSX is typed as well - it's just React.createElement() and you can attach dynamic type checking with PropTypes. Or in typescript

Or you can use them both like described here.

Let's stick to correct usage. Untyped means there are no types or what is the same, there is only one type. For example, assembly is untyped language it has only one type - bit strings, Lambda calculus is untyped language it has only lambdas.

It's impossible to do completely strict types in TypeScript / JavaScript, and there's always going to be that one case that cannot be fixed with this

In general it should be possible. The other question if you want or not. Don't mix up two argument.

typed language such as C++, C#, Java, etc.

You realise that all those languages are not type safe?

Java unsound, C unsound

Haskell has a sound type system. The type system of C (and thus C++) is unsound.

-- cs.uaf.edu/~chappell/class/2016_sp...

C# unsound

No, the C# type system is not sound, thanks to array covariance, my least favourite feature:

-- stackoverflow.com/questions/239391...

It means it is totally possible to write program in all of those language which will crash at runtime because of type error.

Don't confuse static types with type system soundness.

Plus, importing a function makeSureItIsAString seems like overkill just to make TypeScript support complete.

You don't need them everywhere you need them only to validate io e.g. user input, server response etc. There are libraries like, io-ts which helps to simplify this process.

Thread Thread
 
bettercodingacademy profile image
Better Coding Academy

In general it should be possible. The other question if you want or not. Don't mix up two argument.

I wouldn't say "in general", I would say "in theory" - however, in practice it is commonly the case that you don't write 100% of the code you use; and as such, you cannot confirm the validity and "typeability" of the code you are given.

You realise that all those languages are not type safe?

That was not my point, and I overstepped when I said "true type safety". Obviously TypeScript does not provide sound type safety and neither do the languages I've listed; however, they do have much stronger, native checks for static typing that are built into the languages, as opposed to TypeScript which still transpiles down before then being interpreted - quite a few layers there where errors can occur.

You don't need them everywhere you need them only to validate io e.g. user input, server response etc. There are libraries like, io-ts which helps to simplify this process.

Could you give an example of when you would need to validate and when you wouldn't? Seems weird to have to validate whether user input is a string, for example.

Thread Thread
 
stereobooster profile image
stereobooster • Edited

Could you give an example of when you would need to validate and when you wouldn't?

If you expect string and you read from the html input you will get string. But if you, for example, read state from URL and decode it and expect some arguments to be numbers, things can go wrong here. Or if you, for example, use JSON.decode to get response from the server, you need to make sure that response is in correct format.

I would validate all user input, I meant to say, that reading IO is typically not that big compared to other logic of application.

however, they do have much stronger, native checks for static typing that are built into the languages, as opposed to TypeScript

Why do you think so? Typescript is quite advanced type system it is based on latest research (and written by the same people who wrote C#, Anders Hejlsberg for example). So this claim needs a bit more evidence.

The fact that it compiled to JavaScript doesn't make it unsafer. All checks happen before compilation. The same for native programs, check happens before compilation, one of the compilation steps is type erasure (unless you use something like Reflections or io validation or pattern matching on boxed values). After type erasure you deal with untyped assembly code. Do you think assembly is more safe than JS? (rhetorical question)

Collapse
 
sompylasar profile image
Ivan Babak

It's impossible to do completely strict types in TypeScript / JavaScript, and there's always going to be that one case that cannot be fixed with this.

You have to understand where it is impossible: at the I/O boundary where your typed system talks with the outside world. Types help to make sure statically that the typed part of the program does not contain type errors. If the I/O boundaries are clearly delineated, and the data is cleanly marshalled from the untyped world into the typed world, you will clearly see the benefit if the typed world is large. If the only thing you do in your programs is manipulate the untyped data, it is easier without types.

Collapse
 
projektorius96 profile image
LG

All those folks who are on TypeScript side are biased or at least part of TypeScript living standard . I agree with @Better Coding Academy that TS is scam & will be scam because it takes all its fashion clothing (generics, type checking, etc.) off once transpiled to JavaScript before being compiled into something more of assembly taste . I assume nearly best not too much geeky trade-off for JS lander would be to try C# , of course , this is just my personal opinion .

Thread Thread
 
airtonix profile image
Zenobius Jiricek

sounds like you're using too many escape hatches and not qualifying them with runtime type checking too.

A great way to think about typescript is that it will help remind you when your data system isn't as air tight as you think it is.

combine this with a IO typing system like Zod, and you're pretty much gold.

Collapse
 
noderaider profile image
Cole Chamberlain • Edited

With a very strict configuration, TypeScript is more type safe than C#. In C# a reference type can be null. Not the case in TypeScript. With any language you could read in unknown data. It's no different with TypeScript. Use some assertions.

It may not save you time coding (I'd argue it does - see intellisense), but it 💯 saves time in prevention of runtime bugs. If you're seeing red squigglies and don't need to fix them to run your app, you're not doing it right.

If you're explicitly typing everything, you're not doing it right. I'd argue that the TypeScript example with context you posted is more readable due to the ability to read exactly what the context is via the generic type parameter.

TypeScript unit tests are usually shorter and superior to JavaScript's due to there being no point to testing a bunch of silly stuff like does this module export a function or not.

Collapse
 
kayis profile image
K

I learned that if a type checker just let your app crash "right before a bad access" it is equivalent to untyped.

Collapse
 
shavyg2 profile image
shavyg2

Lol, no

Collapse
 
stereobooster profile image
stereobooster

If it allows incorrect type to pass type check process it is called unsound type system, not untyped.

Thread Thread
 
kayis profile image
K

That's not what I meant.

JS says right before an access on undefined that it is undefined. So the dynamic type check could as well be not there.

Thread Thread
 
stereobooster profile image
stereobooster

This exception itself is dynamic type check

VM219:1 Uncaught TypeError: Cannot read property 'sd' of null
    at <anonymous>:1:6

JS type checked it for you and because type mismatched, the only thing it is left to do is "panic" (throw exception)

Thread Thread
 
shavyg2 profile image
shavyg2

It's crazy how clueless some people are. What is confusing is they'll sound so sure when they are talking tho. If the language wasn't type checking it wouldn't crash it'd just keep going with wrong values. Dude said might as well just not be there. If I had a number 98, I think is "a" if I used as a char it would say "a" but because it's typed check, it checked to see how I was using it and crashed so I the developer can be informed and correct my mistake or cast it to explicitly tell the run time no I did this on purpose.

Thread Thread
 
kayis profile image
K

Sounds reasonable, thanks.

Got my definition of dynamic typing == untyped from a static typing fan prof. at university.

"Either you use static typing or no typing at all, everything else is BS."

Thread Thread
 
stereobooster profile image
stereobooster • Edited

this kind of education. I feel you. I had something similar.

(this is addressed to your professor)

What about IO validation?.. This kind of type checking can be done only at runtime. And all "super" static languages do it at runtime, including such notorious examples as Haskell and OCaml.

I mean even if you use static typing, some checks are impossible to do statically.

Also how to interpret no types? If you would take a look at the parser of almost any language, you would see that parser knows about types. It knows that value in quotes is a string, that value from digits is number, etc. In dynamic languages, there can be no declarations of types of function arguments, but there are always types of values. As well even if type declarations omitted they can be inferred by powerful types systems (to some degree).

What about a gradual type system? Which allows having only some of the types declared.

Thread Thread
 
shavyg2 profile image
shavyg2

It's just crazy, I mean I'm sure some of you have worked with JavaScript and feel a bit confident commenting. In my mind I'm like but you see typeerror in JavaScript when you use the wrong type some where or it says type error can't call blah on foo. Then you go on to say it has no types. It's like hearing there was a car crash and being like, I bet you no cars where involve. I just don't get how people say stuff like that. I have a few friends trying to learn programming and they like it's hard man, and I'm like naw people just make it confusing because they say so much nonsense and I don't even understand why. Books and paid online courses are the best route sadly because the internet...

Collapse
 
cubiclebuddha profile image
Cubicle Buddha

Thank you @stereobooster for mentioning io-ts for strong typing at the boundaries of your application. I really think it helps eliminate all of the problems that Lucas mentioned.

Collapse
 
luxcium profile image
Benjamin Vincent • Edited

This is indeed possibly interesting forSure:
null for sure

I am now adicted and dependent to the type sytem... when I do small stuff in JS I always end up changing my extension to .ts because it is way more easy... so the tradeoff you are talking about is exactly waht it is (a trade off) → I am lazy as F'ck so I prefer TypeScript but... it imply that I need to work more so I can relax about the types... The main point is about the information the type brings more than the safety or what else (at leat to me)... if I wasn't lazy and at the same time concerned about safety I would do everything in RUST perhaps...

Collapse
 
woubuc profile image
Wouter • Edited

For me and the devs at my company, Typescript is only partially about the static type checking. The biggest 'win' that Typescript offers is a direct way to communicate and enforce to the other developers how to use the functions and libraries we build. Using strict tsconfig settings and input validation (like @stereobooster mentioned in another comment), there's virtually no way they can implement it incorrectly, unless they force-override the Typescript compiler. The IDE support and integration of Typescript (autocomplete, etc) is also much better than with plain Javascript (at least with the IDEs I've used recently, which are WebStorm and VS Code).

Regarding the example code you gave for the readability argument, you generally wouldn't define interfaces in the same file as your logic. But that may be a necessary React thing, I'm not sure. I work with Vue which has plugins for Typescript class support and decorators, so I generally don't need to define my own interfaces for that stuff.

Perhaps a similar solution exists for React to make working with Typescript easier? The biggest pain point of Typescript is interop with plain JS libraries (especially if they depend on the dynamic nature of Javascript), but most of the bigger libs, tools & frameworks have Typescript support these days (built-in or through the use of plugins like with Vue).

I completely agree with your last point though. No matter which language you use, be it Javascript, Typescript, Scala or Whitespace, following best practices and writing clean, structured code is paramount to a well-working codebase and a good developer experience.

Collapse
 
toastking profile image
Matt Del Signore

For me this is the biggest win of typescript. Types act as another layer of documentation. It encodes valuable information in the code that helps future developers use what you wrote

Collapse
 
alinisarahmed profile image
Ali Ahmed • Edited

As a junior dev on my first job who had to read the code other team members wrote in a project, I can testify to this, TS was a godsend! I was up and running in two days max and able to contribute. The code didn't even have a single comment (that's bad or not is another topic,but I feel with TS you don't need much commenting anyway). Without TS I estimate I would've struggled for a week at least just to understand what was going on. I wasn't sold on TS before, but after this I'm never not using TS in a project. The self documenting aspect of TS is enough to warrant its use in every project, let alone all other benefits.

Collapse
 
bettercodingacademy profile image
Better Coding Academy

Thank you for your response! Like I said, there are cases where I think it is appropriate, including:

If your team is already using TypeScript, if you want to write code for other developers who may be using TypeScript

However, I do personally think it is a hassle, and that there are better ways to communicate coding interfaces across teams and developers. I'd also like to play devil's advocate here; even if you do use TypeScript, an ignorant (or arrogant) enough developer can still make coding standards really hard for your team.

Collapse
 
woubuc profile image
Wouter

We previously used JSDoc comments with type info, which worked fine and is still a decent solution when working in plain JS because most IDEs understand it just as well as Typescript annotations, but Typescript also lets us enforce it instead of just communicating (we still use JSDoc for documentation). Which ways do you prefer to communicate the information?

Along with a very strict tsconfig, we also have a rather strict set of eslint rules, and an .editorconfig file to cover all bases. Developers have to go out of their way by explicitly disabling all these tools to contribute something that doesn't adhere to our coding standards (and even then it'll still get caught by CI). So at that point you're talking about malice which is a whole other discussion.

We do use coding standards based on our common preferences and opinions, to make 'enforcing' these standards as easy as possible on the devs.

Thread Thread
 
bettercodingacademy profile image
Better Coding Academy

As Jeff Atwood said, the best code is the one that is self-documenting. I follow that rule, and I believe that static typing and JSDoc comments just cement in bad code even further (cause then refactoring it takes even more work).

There are certain patterns that become difficult if not impossible to enforce across a codebase. Not using shotgun surgery, for example. I think regardless of how much CI pipelining you do, ensuring the quality of the codebase still comes down to the skill level of the developers, proactiveness of developers with regard to regular refactoring, and the proactiveness of managers in maintaining code review processes and hence enforcing code quality.

Thread Thread
 
cubiclebuddha profile image
Cubicle Buddha • Edited

I agree that JSDocs can get stale, but TS types don’t have that same affliction. Do you realize that you don’t have to explicitly create interfaces? That’s why I’m so confused by this point:

As Jeff Atwood said, the best code is the one that is self-documenting. I follow that rule, and I believe that static typing and JSDoc comments just cement in bad code even further (cause then refactoring it takes even more work).

TypeScript can infer the return type of a function. So it that manner... TypeScript is the most effective language at creating “code as documentation.”

For instance everything in this example is standard JS but when it’s run through the TS compiler it catches the error implicitly:

function createMockUser(){
    return {
         firstName: Bob,
         lastName: Smith
    }
}

const myUser = createMockUser();

console.log(myUser.name.toLowerCase()); // this will cause a compiler error

Update: Based on Edward’s feedback below I’d like to clarify that you have the option of explicitly defining the return type too (more info here). I personally find it amazing that you can have implicit or explicit return types. Is there another language that allows that?

Thread Thread
 
etampro profile image
Edward Tam • Edited

No. That does NOT make TypeScript the most effective language at creating “code as documentation.” simply because it can infer returned types from the function, because you can always implicitly return the wrong thing.

And put aside whether liking typescript or not, this is the attitude that leads me to dislike the typescript community. The title says "change my mind", and you are definitely not changing anyone's mind.

Thread Thread
 
cubiclebuddha profile image
Cubicle Buddha • Edited

Edward, my goal is to help people to get happier at work. For me, part of that happiness equation is TypeScript. If I’m not being convincing, then please let me know how I can better be of service to the larger community. I want people to understand more. If through that understanding people discover that TypeScript isn’t right for them, then I’m happy. If they discover that TypeScript is right for them, then I’m happy too. So please let me know what I can do. Is there a type of problem or example situation that I can illustrate with a code example?

Thread Thread
 
etampro profile image
Edward Tam

This tone is better, and I appreciate that.

I work across multiple programming languages over years, and I think that every language has its own philosophy and its own way to achieve certain objectives (either it being the best is subjective).

Typescript is one language that I have to work with closely recently. While I appreciate some of the good things TS can bring to developers, I wouldn't say it is one-size-fit-all language for all the practical use cases.

In this particular discussion, I think a elaboration of how you can achieve "code as documentation" with inferred types in TS with some code example would be helpful. (Though I personally thing proper unit tests and JDoc would server better in this particular aspect, and it is not a TS specific thing).

Thread Thread
 
cubiclebuddha profile image
Cubicle Buddha • Edited

I updated the original comment with examples. I don’t understand the “tone” comment though. If you’re reading my comments and assuming that I have some kind emotion behind them, then that’s a tone that you’re projecting onto it. My goal has always been to spread knowledge and enthusiasm.

As for the testing comment, every professional project I’ve developed recently has over 75% test coverage and it uses TypeScript. Why does everyone bring up testing vs types like they’re mutually exclusive? I like both. A lot.

Thread Thread
 
etampro profile image
Edward Tam

I do not think testing and typing are "mutually exclusive". But one of the "pros" people keep pitching about Typescript is the "code as documentation" and "less error" talking point, which I think is already achieved by having proper unit tests whether the language is typed or not.

I could be biased here, but just talking about this specific "merit" Typescript can give is not convincing to me. It could be also due to working style, because I tend to write very thorough unit test coverage (~98% across the projects I developed in the past few years).

Collapse
 
shavyg2 profile image
shavyg2

Don't feel insulted here.
Imma lead with that.

Every now and then you gotta be like, huh and listen to what people are telling you and learn from it.

I don't wanna sound condescending, I was kinda like that when I was younger too pushing my own thoughts. Honestly, listening is an important skill. Learning is an important skill. Being able to take a step back is an important skill.

There are many things in this post that just plain wrong.

There have been some follow up articles about this post that explain what is wrong about it. Read them. They are not opinions btw. As I said plain wrong.

I really hope you take the time because honestly it's a long post. I know you put time in to get it out and not everyone can sit down and do that.

It means you care which is key to getting to the point where you can do amazing things.

Caring is something you can't teach. You can't inform a person, they just have to have it or not.

Listen, to what people are saying and look at it again, perhaps it will give you some time to think. Perhaps write another post afterwards.

At the end of the day I'd rather a person misinformed than one that doesn't care.

Look into it and then come back, wish you the best on your travels.

Collapse
 
ssalka profile image
Steven Salka

Have you ever worked with a piece of JS code and thought any of these?:

  • "I wonder what fields are in this object"
  • "I wonder what exports are available in this module"
  • "I wonder if I can pass an object instead of a string here"

I certainly have, and all 3 of these things (not to mention several more) slow me down and annoy me as a JavaScript developer. Oftentimes I would have to dig through 3 (sometimes 5+) files to see where an actual value comes from, and sometimes even it comes from an external service that has little or no documentation about its return types.

In TypeScript - unless you are dealing with anys - the problems go away and your IDE or terminal can give you answers to these questions in real-time. Huge productivity boost.

That is why I will never again work on a codebase that doesn't leverage static typing.

Collapse
 
eliashdezr profile image
Elias Hdez

This.

I have the experience that people that behave like OP in thinking "this is a waste of time tool I prefer raw", usually is people that think their code is a piece of art and there's no imperfection on it, which translates later in a disaster code base.

Collapse
 
bigredmonsteruk profile image
Big Red Monster • Edited

Have you tried using an IDE that does this for you with JS though?

New developer on our team is trying to convince us to switch to Typescript with arguments like this. He has only ever used VSCode (which is terrible out the box for JS) and was trying to impress me with its intellisense. I then showed him IntelliJ and atom which have been doing the same since before TS was born.

I realise I am now in quite a luxurious environment where we use ES6 modules and current functionality with good IDEs. Many people seem to have written JS 5 years ago and are coming back to Typescript with the impression it's that which has somehow "fixed" JS. Almost all the good benefits boil down to things JS now has / VsCode support.

I am currently loving development with ES20## no build step in dev / Babel . Typescript just adds an unweildy and (IMHO) really bad typing system on top and enforces a build step. They could have at least looked at Hindley–Milner types and languages that use them rather than running with what they have.

Collapse
 
xcs profile image
Cristian

I strongly disagree with the article. For me it just looks like a really biased article created just for the sake of having a conversation started (which, comparing the number of likes to the number of comments, it successfully achieves).

Just to enumarate some things that are orders of magnitude faster/better with TypeScript than with plain JS:
1) Refactor code across multiple files.
2) Autocomplete quality.
3) Catch A LOT of errors while you type. The ts strict mode can save you hours of pain and reduce the number "can not read property X of undefined" errors to almost none.
4) For the libraries that come with typings (most of them) you have a much higher chance of using them as intended and always passing the correct parameters. Even if you read the docs, without typings you might pass the parameters in the wrong order, or forget to wrap a variable in an Array.
5) Writing more robust OOP code. Try extending classes, implementing interfaces, having virtual methods and other useful OOP practices in plain JS. Your code will crash a lot at runtime. Yes, you can add checks for abstract classes and implement your own virtual functions, but that doesn't really save time over TypeScript, does it?

It's just like saying you shouldn't use a linter, as it's your job as a programmer to write readable code, research and respect all good practices, while also stating that trying to use any external help to making that happen is bad.

Yes, TypeScript does slow you down if you don't know how to use it and it takes time to learn it, but so does every new language. Once you learn it, it will actually save you time in the long run, not waste time as mentioned in the article.

Saying that typos and other human errors "can generally be caught by an experienced programmer anyways." is like saying a professional athlete never makes mistakes. Yes, it makes them less often, but no human is perfect.

With regard to more complicated issues (e.g. race conditions, memory leaks, etc.), TypeScript is completely useless.
No one advertised TypeScript as being a solution to those problems. For it's the same as bashing CSS that it does not help with fixing HTML DOM update performance issues.

The article also mentions that TypeScript is pretty useless for a senior developer as they can write good code anyway and notice all errors while typing, but I have a strong feeling that the more senior a dev is, the more likely it is that he actually uses TypeScript.

I do think, and if I remember correctly it's also mentioned in the article, that the author never used TypeScript in a medium/large multi-person project, because, once you do, you realize how often you get to think: "wow, if we weren't using TypeScript, fixing those issues would have taken so much time".

Collapse
 
pozda profile image
Ivan Pozderac

this is exactly my opinion! I just wanted to reply to whole article with simple question: is linter also waste of time? but you also covered main points that I strongly agree with.

Collapse
 
yaser profile image
Yaser Al-Najjar

Brilliant one, Lucas 👌

It's just so simple:

Wanna write clean code?

Learn how to write "clean code", NOT "static typed code".

Wanna write more reliable code?

Learn how to write tests.

Collapse
 
stojakovic99 profile image
Nikola Stojaković

No matter how clean code you write, once you reach certain threshold you'll run into problems with JavaScript. There is a good reason why it's one of the most hated languages, and TypeScript makes working with JavaScript codebase much easier in the long run.

Collapse
 
bettercodingacademy profile image
Better Coding Academy

Do you have evidence to back up your claim? My admittedly personal experience with tens of thousands of lines of typed code would lead me to believe otherwise, however I'd love to hear your side of the story!

Thread Thread
 
stojakovic99 profile image
Nikola Stojaković

This is my personal conclusion reading the experiences of more experienced software engineers + my personal experience working on the custom Node.js e-commerce platform.

I believe that, once you reach certain point in the project (I'm not talking about specific number of lines of code nor any other specific metric), dynamic typed language will actually slow you down a bit, because you'll deal with errors which would be eliminated right at the start in strongly typed environments. Of course, I'm not saying that this could be a substitute for following good practices, but it's much easier following good practices in a language which enforces good practices and prevents yoy from making stupid mistakes, like adding number and string. Yes, you should write your code in a manner that won't allow such things to happen that much, but from a personal experience, this is much more easily done in TypeScript, and even though I had to write more code, in the long run it made me more productive.

Nevertheless, I would like to hear your experience from working on huge codebases in JavaScript (or any other dynamic typed language) and the ways in which you addressed such problems. If I had to write enterprise level software my first choices would definitely be static typed languages, and not TypeScript, but if I had to work inside JS ecosystem, I would definitely choose TypeScript for such task.

Thread Thread
 
aerorezo profile image
Aerowyne Rezo

Lucas, do you have evidence to back up you claim? Historically, speaking most JS engineers I know forget that the code on nome_modules wasn't written by them yet still count it as lines of code.

So it would nice do see your proof, remember you are defending your thesis here.

Thread Thread
 
stereobooster profile image
stereobooster • Edited

Do you have evidence to back up your claim?

Here you go blog.acolyer.org/2017/09/19/to-typ...

TL;DR: both Flow and TypeScript are pretty good, and conservatively either of them can prevent about 15% of the bugs that end up in committed code.

cc @yaser

Thread Thread
 
yaser profile image
Yaser Al-Najjar

I haven't gone through the research paper, and I skimmed the article real quick...

Could please correct me if I'm wrong:

Out of 3 million bugs they picked only 400 and studied them to reach that conclusion, right?

Thread Thread
 
stereobooster profile image
stereobooster

3M is the number of github issues, not all of them bug fixes. Researches were forced to recheck manually if it is a bug fix or not

Each is then manually assessed to determine whether or not it really is an attempt to fix a bug (as opposed to a feature enhancement, refactoring, etc.)

but they picked enough of them to make sure this is statistically significant result

To report results that generalize to the population of public bugs, we used the standard sample size computation to determine the number of bugs needed to achieve a specified confidence interval. On 19/08/2015, there were 3,910,969 closed bug reports in JavaScript projects on GitHub. We use this number to approximate the population. We set the confidence level and confidence interval to be 95% and 5%, respectively. The result shows that a sample of 384 bugs is sufficient for the experiment, which we rounded to 400 for convenience.

Thread Thread
 
stereobooster profile image
stereobooster

If you want more researches check this article dev.to/baetheus/thank-you-next-typ...

Thread Thread
 
aerorezo profile image
Aerowyne Rezo

@stereobooster I wasn't asking for support that type systems finds bugs, I was asking that the author of the article defend any of his points. :p

However, if I were to extrapolate the information from that article it would be that two years ago, when TypeScript was still new and lacking a large following (not many public modules were properly typed back then), it still had a significantly positive impact. If they ran that study again today I would imagine the results to be significantly higher, just from the new features in TypeScript let alone the number of fully typed libraries that now exist in DefinitelyTyped.

Thread Thread
 
yaser profile image
Yaser Al-Najjar • Edited

Sorry for my late reply, and thanks a lot @stereobooster for the explanation 🙂

Besides that the researcher is a guy from Microsoft (which could make the research a bit biased), and I'm not a math expert.

But the confidence interval is affected by the variation & the sample size.

And, I find 400 bugs to be a ridiculously small sample size and you know that bugs can vary to an infinite interval.

Of course static typing would discover some bugs, but everything comes at a price.

The Price (blind spot that the research is not looking at):

  1. Supposing the numbers were very accurate, Is the extra effort (using static typing) worth it (the discovery of 10% bugs)?

  2. That 10% of bugs, are they really hard to discover bugs? or just ones that you would open the browser and you would find them right away?
    Generally, bugs that devs find valuable to discover are the logical ones, not the syntax or statically-typed ones.

  3. Typescript would require you to write more code.

And hey, LOC (lines of code) is a liability, NOT an asset... means that extra code need to be maintained.

I just started a discussion from a different angle here (feel free to join):

Thread Thread
 
yawaramin profile image
Yawar Amin • Edited

Besides that the researcher is a guy from Microsoft (which could make the research a bit biased

Yaser, firstly, there are three co-authors on the 'To type or not to type' paper, and two of them are listed as being at the University College London, and one at Microsoft Research. Now, you could argue that the Microsoft Research guy is pushing TypeScript because some other team in Microsoft makes it. Far-fetched, but sure. So then why would the paper say that both TypeScript and Flow were about equally effective? Flow is made by Facebook. Wouldn't that go against your bias argument?

But the confidence interval is affected by the variation & the sample size. ... And, I find 400 bugs to be a ridiculously small sample size

Well, that's how statistical analysis works. You don't need to trust this paper, calculating a sample size for a statistically-significant result is a well-known technique. Go to surveymonkey.com/mp/sample-size-ca... and plug in the numbers (population size 3 million, confidence level 95%, error margin 5%), you will get the same sample size 385.

The Price (blind spot that the research is not looking at):

Nope, they looked at it.

Is the extra effort (using static typing) worth it (the discovery of 10% bugs)?

The extra effort was timeboxed deliberately: they decided to look only at bugs that could be fixed by applying very simple types within a 10-minute window.

are they really hard to discover bugs? or just ones that you would open the browser and you would find them right away?

These were bugs that were shipped to and reported in production. So they passed all quality-control methods that the projects already had in place.

Typescript would require you to write more code. ... And hey, LOC (lines of code) is a liability, NOT an asset... means that extra code need to be maintained.

Unit tests also require you to write more code. That's a liability, don't write unit tests! ;-)

Collapse
 
yaser profile image
Yaser Al-Najjar • Edited

Nikola, my friend...

It's not right to assume that there is some "threshold" without having a solid proof (aka running into one).

Cuz really, tons of companies are doing just fine with the normal JS... not just fine, but actually PERFECTLY FINE.

Even us (Coretabs Academy), we are doing really great with the normal JS, and we super barely have problems.

I mean, before throwing such assumptions about "long-run" and "large codebase", please try it and see how it goes.

Thread Thread
 
stojakovic99 profile image
Nikola Stojaković

Hey Yaser,

I don't know why you think I'm just assuming it - I actually have experience working with a bigger code base written in JavaScript and TypeScript (our front-end part is written in JavaScript, and back-end is in TypeScript).

I doubt anyone can give a specific proof for this and we can all talk from our experiences. As I answered before, this is my experienced combined with the stories I have read on this topic (dynamic vs static / strong typed systems) written by more experienced software engineers and I'm definitely not saying this is something written in rock and I would like to see examples where this is not true.

Right now I'm working on an e-commerce system written in TypeScript. I don't know how much lines of code it has nor I think it's important here. What I can say for sure is that it makes me much more productive to know upfront if there is some potential problem with my code instead of running into problems in runtime. Time which I would have to spend debugging the problem may not be high, but it adds pretty quickly. At the start it took me more time to properly structure my code, but in the long run, I believe I saved much of my time.

I'm not saying that just using JavaScript will bring you the problem - what I'm saying is that bigger, properly structured TypeScript code base will prevent you from running into the problems which could happen to you more often with the same code base written in JavaScript.

As I said before, writing in strong / static typed language is not a substitute for the proper structuring of your code base, but my personal experience is that it's much more productive to write and manage huge code bases in TypeScript than in the JavaScript. If you think otherwise, I would like to hear your experiences on this topic too.

Thread Thread
 
maxinertia profile image
Dorian Thiessen

we super barely have problems.

2vue.runtime.esm.js:1887 TypeError: Cannot read property 'members' of undefined
    at e.r (about.js:259)
    at e.value (siema.min.js:1)
    at s.next (about.js:111)
    at click (about.vue?1da6:1)
    at nt (vue.runtime.esm.js:1854)
    at HTMLImageElement.n (vue.runtime.esm.js:2178)
    at HTMLImageElement.Yi.a._wrapper (vue.runtime.esm.js:6876)
it @ vue.runtime.esm.js:1887
rt @ vue.runtime.esm.js:1878
tt @ vue.runtime.esm.js:1839
nt @ vue.runtime.esm.js:1861
n @ vue.runtime.esm.js:2178
Yi.a._wrapper @ vue.runtime.esm.js:6876
about.js:259 Uncaught TypeError: Cannot read property 'members' of undefined
    at e.r (about.js:259)
    at e.value (siema.min.js:1)
    at about.js:76

This is from your site.

If members had type Member[]? this would have been caught by typescript, and you'd be forced to check whether it was defined.

It only took me a minute on your site to find that, what else do you suppose is lurking in there that could've easily been caught pre-runtime?

Thread Thread
 
yaser profile image
Yaser Al-Najjar

Thanks Nikola for sharing your view, I really understand what you're saying.

My point of view about TS is that it adds extra code... and from my experience: extra code = more work and more time consumed (no matter how it is).

I always see the LOC as a liability, not an asset.

I don't know why you think I'm just assuming it - I actually have experience working with a bigger code base written in JavaScript and TypeScript

I saw your GitHub has 17 contributions in the last year (and mostly on non JS code), it's something you might want to change... cuz people do judge on that (sorry for judging too fast).

I'm not saying that just using JavaScript will bring you the problem

You just laid your hands on the blind spot that I saw in this whole discussion (from other devs in this topic).

Which is (dynamic vs static) typing langs will solve the problem, it's not.

I believe the whole discussion should be about the architectural & design decisions and the developer expertise.

Yes, you're absolutely right about how TS introduces better design decisions.

I faced exactly the same experience when using C# then Python. I said C# (and ASP Core) tells you exactly how to do things, but Python gives you all the flexibility and power to do things in anyway.

In time, I realized that I finish my projects in Python on time much more faster that what I did on C#!

Why? cuz I transferred that knowledge (of doing things the right way) from C# into a language that allows me to do me doing things in anyway.

And that is ultimate power, and the only catch is as you know:

With great power, comes great responsibility

Thread Thread
 
yaser profile image
Yaser Al-Najjar • Edited

@maxinertia

This is from your site.

Does that affect the end-user in any way (would he see any unexpected result)? NO

Then, do I care? NO

Thread Thread
 
stojakovic99 profile image
Nikola Stojaković

Yaser,

Just because something doesn't affect the user now, doesn't mean it won't affect it later or cause another, seemingly unrelated error.

Thread Thread
 
eliashdezr profile image
Elias Hdez

That was hilarious, you caught him off guard with that bug.

Thread Thread
 
kevinclarkadstech profile image
kevinclarkadstech

“It only took me a minute on your site to find that, what else do you suppose is lurking in there that could've easily been caught pre-runtime?”

Hahahahahahaha hahahaha hahaha 😂 these fools with their “TypeScript is not helpful” crap. 💩I can just imagine how hard it would be to understand their codebase.

Thread Thread
 
worc profile image
worc

...undefined objects during runtime aren't necessarily going to be caught by your static type checker. if the api changes and leaves out that key object, what good did your type system do?

Collapse
 
woubuc profile image
Wouter

You can write clean code and still find static type checking helpful. These aren't mutually exclusive.

Collapse
 
yaser profile image
Yaser Al-Najjar

Who said that "they are mutually exclusive"?

I just stressed on focusing on the goal (clean code),

Cuz "static typed code" != clean one

And hey, many people just mix those two!

Collapse
 
g1itcher profile image
G1itcher

Typescript enforces better coding practice by design and prevents the kind of crazy stuff you see in JavaScript projects.

If you work in a company with contractors or developers at multiple levels of ability, TS will always increase productivity across the team.

Articles like this usually seem to forget that people are inherently fallible and lazy. TS enforces rules that keep the windows from being broken (to steal the uncle Bob metaphor)

Collapse
 
bigredmonsteruk profile image
Big Red Monster

"Typescript enforces better coding practice by design and prevents the kind of crazy stuff you see in JavaScript projects."

I haven't found that to be true tbh - Almost all Typescript projects I have both seen and been a part of seem to follow standard class based organisation. I would argue that Typescript really pushes people down the class route and then they end up with the same old problems with classes we've all had with large codebases and classes.

Now - you can definitely CAN work without classes in TS but if you say it "enforces better coding practice by design" I would have to disagree. It is most definitely not a crutch for inexperience.

Collapse
 
bettercodingacademy profile image
Better Coding Academy

Well said. You rewrote my whole article in four lines!

Collapse
 
eliashdezr profile image
Elias Hdez • Edited

This is called "subjectivism".

If the majority of people thinks that TypeScript is awesome and productive (according to surveys), then so be it, why try to convince people otherwise because you don't agree with it? We don't need to change your mind and neither us.

All the comments in this "article" are just that, subjective, including mine. The only positive thing here is people pointing out good points based on actual data, not assumptions like this article.

Collapse
 
trusktr profile image
Joe Pea • Edited

A few points you haven't covered:

1) Code refactoring. TypeScript paves the way here. I once refactored some UI code from 1400 lines of typed jQuery to 700 lines of React. I didn't test or even run my code, but I pushed it to a branch and my co-worker pulled it and told me it worked first try and passed all QA. It would have taken much longer to refactor with plain JS, and likely would not have worked first try. From completion in JS, to completion in templates (JSX) to completion in the styles (CSS-in-JS), the refactoring was a total breeze. I have never had such a good time doing major JS refactoring until I used TypeScript.

2) Communication: more than anything, types allow cross-developer communication with nothing but code. Interfaces tell other people what you intend (without them having to open a separate test file for example). It saves time in understanding code. This is important, for future devs coming onto a project (and previous devs leaving).

I think you'll appreciate TS more when you consider those aspects.

Collapse
 
dwd profile image
Dave Cridland

You're almost immediately destroying your own arguments - all of them - in just one phrase:

"can generally be caught by an experienced programmer anyways"

So your implication there is that if bugs get through that Typescript would have (trivially) stopped, it's because the programmer isn't experienced enough? It's not the code, it's the developer?

In that case, after 25 years of writing code, I'm not experienced enough by your definition.

Maybe you're too good a programmer to need static typing. Maybe you don't need unit tests, either. Maybe you don't need automated tests. And if you do, perhaps you should take your own advice and "learn to write better code".

But as for myself, I'll take all the help I can get - I might not be experienced by whatever definition you use, and I'll readily agree I can always learn to write better code, but what my experience does tell me is that static typing is useful both to me as a programmer, and also my IDEs and other tooling, which in turn make up for my weaknesses and let me concentrate on providing actual value to actual users.

Collapse
 
trmaphi profile image
Phi • Edited

Just being curious, do you prefer compilation error over run-time error? If the answer is the compilation error, I'll say TypeScript is not that bad.

The thing I found most valuable about TypeScript is I can check error on compilation, the required properties on a type/interface already save me and my team hours of debugging, without a doubt if I need to prevent developer errors, this is my life-saving.

And the second thing, I found is that you can use untyped JS in TypeScript. It gives you the option of any and @ts-ignore. Sometimes, I do this just to code faster, I come back later to fix the problem of TypeScript warnings. So, TypeScript give you the power and also the options.

Collapse
 
shavyg2 profile image
shavyg2 • Edited

Typescript may not be for you, but what your saying doesn't make any sense. You sound like you work alone more often. I remember getting a snippet of js and not having a clue what was what. I was like console log the variables and send it to me. I remember getting typescript code and instantly knew everything that was going on. So static languages are for static analysis, it's not about run time type checking for typescript.

Typescript makes code readable because it describes the content of the code in the lease possible way, compared to using jsdoc, and typed js has been proven to have less bugs. It's not typing that slows development it's bugs. Look it up

Collapse
 
quanla profile image
Quan Le

Typing is a great idea, but no implimentation has proved that it works in practice. Typescript is so flawed that it destroy coding experience totally.

From someone who was so annoyed by wrong TS error messages, and had to add too many ts ignore comments

Collapse
 
yawaramin profile image
Yawar Amin
Collapse
 
quanla profile image
Quan Le

So TS is always correct and never gives stupid errors? Even TS team doesnt believe so, that's why they have ts-ignore.

Sure, every newbie's code are swamped with simple mistakes, and simply fixing those typos can make the code "run". That gives you the immpression that the compiler is life saver here. And that is ahuge delusion

Thread Thread
 
yawaramin profile image
Yawar Amin

If you use it properly, it should be very rare to get a 'stupid' error. Almost every type error is saying something interesting, in my experience. ts-ignore is not something unique to TypeScript, every language provides escape hatches from their static checks. E.g. Rust's unsafe and Haskell's unsafePerformIO, etc.

Thread Thread
 
quanla profile image
Quan Le

First, why are you so sure that I am not using it properly? Is it that difficult to use a compiler "properly"?

Second, great. Thanks for the point. It helps explain why all static language is failing at a certain level.

Cheers

Thread Thread
 
yawaramin profile image
Yawar Amin

Is it that difficult to use a compiler "properly"?

Actually, it kinda is difficult. You have to put in some work to understand the type system, error messages, idioms, how to take maximum advantage of static types and their intersection with dynamic values. No such thing as a free lunch.

all static language is failing at a certain level.

Well here's the thing. Static languages have an escape hatch to allow dynamic behaviour. However dynamic languages don't have an 'escape hatch' to allow static behaviour. So really, by sticking to dynamic only, we are limiting ourselves.

Thread Thread
 
quanla profile image
Quan Le

Right. Thanks. With your reasoning even eating lunch is difficult, you have to learn which one you have to chew and which one you have to swallow immediately, and how to have both together for maximum eating joy...

Sorry for the sarcarsm, but man, using static type is just the easiest thing in programming ever.

Anyway, goodluck with programming

Thread Thread
 
yawaramin profile image
Yawar Amin

using static type is just the easiest thing in programming ever.

So it's really easy and it can be helpful ... I don't get it, in that case what's your argument against it?

Thread Thread
 
quanla profile image
Quan Le

Did I say it can be helpful? Maybe, for people who cant determine what type of variable he is looking at. But for me, and the author of this article, TS is doing more harm than good. And it is like a pain in the ass using TS every day

Thread Thread
 
yawaramin profile image
Yawar Amin

Ha ha, OK, best of luck to you as you are obviously a programming superstar who doesn't need any help from a typechecker.

Thread Thread
 
quanla profile image
Quan Le

Yeah, sorry if I sound like a jerk, but I had my years with static typing already. At first things are super nice, but then shortcomings start to appear, and now, it totally outweighed the good stuffs.

So yes, typechecking does help here and there, but the tradeoffs are far too big for me. So, no thanks

Collapse
 
newtonmunene_yg profile image
Newton Munene

I think it all boils down to personal preference. Personally, I feel it takes way longer for me to setup babel and other polyfills than to get started with typescript. It also shortens the amount of time I spend debugging as the compiler and linter catches most syntax errors. I am a junior developer, fairly new actually, so I might be wrong but what's the harm in using typescript?

Collapse
 
bettercodingacademy profile image
Better Coding Academy

Thank you for your response!

Setting up Babel is (mostly) a one-time thing, and is generally mitigated by using bundlers such as Parcel (assuming you're working with the frontend). However, using TypeScript incurs a constant tax of about 20-40% of extra development time (in my experience), so definitely tread wisely.

Collapse
 
cubiclebuddha profile image
Cubicle Buddha • Edited

Explain this “tax” objectively please. And do not cite Eric Elliot’s article since all of his citations have been refuted. The authors of his citations have come out publicly and stated that he is misusing their information to prove the opposite point. The original studies showed that static type checking does improve delivery time.

Thread Thread
 
bettercodingacademy profile image
Better Coding Academy

Like I said, this is "in my experience" :) I definitely am not speaking from statistical evidence. However, like the point I made in my article... writing TypeScript is definitively, provably longer than writing normal JavaScript, so if you are to defend TypeScript and how good it is, the burden of proof is on you to indicate that there is in fact a speed-up to using TypeScript vs. using JavaScript.

Sorry for not explicitly responding to your other items - some of them don't have a "Reply" button and I'm not sure why that is 🤷‍♂️ However on your other point regarding renaming a variable, I'm very curious... could you please describe how TypeScript specifically allows you to rename a variable better in 78 files than with regular JavaScript?

Thank you for your time!

Thread Thread
 
cubiclebuddha profile image
Cubicle Buddha

Right click “refactor > rename” and VSCode does the rest because it’s aware of TypeScript’s instrumentation of the code.

Thread Thread
 
bettercodingacademy profile image
Better Coding Academy

I can do that with regular JavaScript as well though... isn't this an IDE feature as opposed to a TypeScript feature?

Thread Thread
 
cubiclebuddha profile image
Cubicle Buddha • Edited

Webstorm can’t do this effectively in Javascript. Anyone who has tried that (as I have) will discover that WebStorm gets it wrong because it can only make guesses. However when you provide the IDE with the instrumentation of TypeScripts types then the IDE can be 100% accurate. Yes it’s an IDE feature (which I stated in my original message). So that’s why a failed refactor in JS would necessitate a regression tests of the system.

Thread Thread
 
cubiclebuddha profile image
Cubicle Buddha

I think it’s wise to consider the trade-off between the initial development costs and then maintenance costs. That’s why I find comments like this concerning:

However, like the point I made in my article... writing TypeScript is definitively, provably longer than writing normal JavaScript

Yes, I can write it faster in JS. But when I fix one bug and it uncovered another bug... that takes more time in total. Each subsequent bug that’s created takes even more time. However, if you just wrote the app in TypeScript the first place then the subsequent bug fixes can be identified by the compiler. Which means:

  • less manual regression tests need to be run
  • bugs that are caught by the compiler are fixed before they even enter production
  • since you don’t have to fix production bugs you can do so with calmness. Doesn’t everyone want calmness and peace? I’d take that over initial development speed any day.
Collapse
 
redtaped profile image
Jamieson Rhyne

I agree with you in some respects, especially if you have small private methods, typing everything may have diminishing returns.

What sold me on typescript is that it can be used without typing and automatically start giving intellisense and compile errors when passing invalid parameters. So you can add value, even without typing. Then, some models are reused throughout an app, typing commonly utilized models makes things easier for developers to understand the public methods of your well designed, encapsulated classes, without ever having to look at the code to understand the data needing to be sent in. This can be true with primitive types also, on public methods used throughout your app. Having a method clearly indicated as accepting a certain type of data not only gives you type safety which can prevent bugs, but it also make it easier for other developers to understand the code without opening up the class and reading it.

Collapse
 
kayis profile image
K

I didn't grow fond of TS either.

While I have the firm believe that JS doesn't mix well with my aversion of TDD, TS is just too C#-y for my taste.

At the moment I'm looking into Reason which seems much more syntactically minimal.

Collapse
 
vimmer9 profile image
Damir Franusic

No disrespect to you or Typescript, it is a good idea which should lower the number of errors and fight undefined behaviour. I still don't really like that full stack hype and although I have a history of doing quite complex stuff in React and Node, I still prefer php and mysql as a backend system. All this constant changes, patches and updates have led me to quit the UI dev and go back to low level C, statically typed, compiled and dangerous language hehe 😉. I understand the progress and updates are necessary but I feel that something if fundamentally wrong, UIs require too much power to run; the only step in the right direction is not Typescript or Flow, but WebAssembly.

Many developers these days will probably dislike this comment, but for someone who started programming 20 years ago, I consider myself capable of objectively describing the progression of technology.

What is still mind boggling is that we have so many(too many) programming languages to choose from for all projects other than Web UI. For this very reason, I am an advocate of WebAssemnly because if nothing else, we will at least be given an option to use something other than JS for Web client UI.

P.S.
I know there's a myriad of Web scripting languages out there, but in the end, all of them are just transpiled to JS 😒

Collapse
 
fnky profile image
Christian Petersen • Edited

Here's my thoughts on the subject: Development time is not calculated by how much code you have to write but rather by how fragile or error-prone writing that code is.

You have to take a look at the trade-offs that statically typed languages have for your code, your team and how things are communicated. It's important to question yourself and the team on:

  • How do you handle API changes—both for the projects, but also for shared code as well as network data?
  • How do you communicate breaking changes that may affect other parts of the product?
  • How do you onboard future maintainers and developers of this code?

A lot of these questions can be largely solved by having type information at your disposal.

Code patterns does not solve these problems. Why? Because we are human and humans make mistakes. All the time, by nature. It does not matter how secure and restrictive your environment is, there will always be a chance of failure.

But the question is what types of failure this is, and how easy they are to avoid either before they happen, but also how that can be remedied after they happen. Some failures are more destructive than others and you have to consider the pros and cons, depending on the type of product that you make.

Avoiding Undefined Behaviour

Statically typed languages can help you avoid undefined behaviour in most common cases. Since you consume the contracts that types and interfaces gives you, it is almost impossible to fall into a rabbit hole of passing wrong data types around and cause unexpected problems that can be hard and tedious to debug.

Discoverability

Statically typed languages provides ways to define contracts, that can be passed around in a program to ensure that at any point where the data flows, you can ensure that integrity of how that data can be consumed.

This also has the benefit of being extremly easy to use an API, without having to consult to external sources or documentations. With types, you don't need to inspect implementation details since the input and output is documented and available upon usage with intellisense and code completion.

Guards can provide safety to public APIs

If you provide a public API that is to be consumed by JavaScript, you can either write guards manually or use a bundle plugin to handle this for you, based on the available type information.

However, in a project that is purely TypeScript and not meant to be consumed by a public audience, these guards only adds more weight.

Inference is your friend

TypeScript uses inference to guess the types of values that you pass around. In 95% of cases, it works really well and you won't need to define type information, given that your code is written in a way that the inference can understand and follow.

This can help you write better code, too, that is deterministic, since that is how inference work.

Of course you can always get around it by forcing your code style, but that comes at a cost that you have to manage the type information yourself, for example by casting or provide types to declarations.

Collapse
 
brunobrant profile image
Bruno Brant

Lots of strange terminology being used throughout the discussion.

There are two axis when it comes to classify languages relating to its type system:

Weak vs strong - weakly typed languages are those that allow us to cast between types forcibly. C++, for instance, allow us to cast anything to void and cast void to anything, which can lead to type mismatches.

Static vs Dynamic - static typed languages are those which the types are know at compile time, either explicitly (C++, Java, etc) or implictly (F#, etc). Dynamic typed languages means that types are determined during runtime.

Nullability Nullability is a whole other matter. Null isn't really a type, but it's a property of a variable that denotes "no value". Some static type systems incorporate Nullability better than others, like TypeScript, as some users mentioned, where you can inform the "compiler" whether or not the variable (not the type) can be null. This is similar to how mutability is treated by some languages like F#, where you need to explicitly inform that a variable can be mutated.

The point of the article is the usual one: whether annotating types is worth the effort.

First one must realize whether she believes that validating the code automatically is important. If it's enough to launch the application and test it manually, then the discussion is void.

But throughout the last decade we realized that validating our programs using automated mechanisms are a very good practice and worth the trouble.

I believe that statically typing works in the same problem domain: catch programming errors as early as possible.

If, however, you prefer to write tests with all variable combinations (and check types explicitly in code), there's no need type your code.

However, there's one additional feature that I love about typing: the better code completion/suggestions we get. This may be solved in the future when IDE get even better at type guessing, but for now they are limited when types aren't informed somehow.

Collapse
 
stereobooster profile image
stereobooster

static typed languages are those which the types are know at compile time

Right. If you open source code of almost any parser you would see that parser knows type of the value at the moment of parsing ("afsd" - string, 123 - number, etc.). By this definition JS is statically typed.

Dynamic typed languages means that types are determined during runtime

If you would use reflection in Java you would be able to determine type at runtime. So Java is dynamically typed.

Weak vs strong

Not CS terms.

Null isn't really a type

Null is a value. "Nullable" type represents set of one value.

type NullableNumber = number | null
Collapse
 
brunobrant profile image
Bruno Brant

OMFG, what the hell are you talking, son? Is this flame bait?

Right. If you open source code of almost any parser you would see that parser knows type of the value at the moment of parsing ("afsd" - string, 123 - number, etc.). By this definition JS is statically typed.

That's not it. Your examples are values, not variables. Please consider:

function foo(bar) {
   console.log(bar)
}
Enter fullscreen mode Exit fullscreen mode

What's the type of bar? It could be string, number, object, etc. The interpreter will determine it during run time and emit the code to support it accordingly, so if you call foo("abc"), foo(1), and foo({}), you get three compiled code blocks that the interpreter determined during runtime that they where required.

In case you are still not satisfied, check this code:

switch (new Date() % 3) {
   case 0: foo("abc"); break;
   case 1: foo(1); break;
   case 2: foo({}); break;
}
Enter fullscreen mode Exit fullscreen mode

If you call that code, during runtime the JS engine determines the type of the variable bar.

That's the definition of dynamic typing. Types of VARIABLES are not known/determined until runtime. That means that code can fail in runtime, not compile time, if a invalid type is provided.

If you would use reflection in Java you would be able to determine type at runtime. So Java is dynamically typed.

I may not have been clear, so: not you, the programmer. It's the compiler that doesn't know the type in compile time. Java is statically typed because all variables have type that are statically defined in compile time.

One more fundamental thing to note: variable type doesn't change in static typed languages, whereas they can change in dynamic typed languages. Check this code:

// Java/C/C#
int num = 10;
num = "abc"; // compiler error
Enter fullscreen mode Exit fullscreen mode

However, this JS code is valid:

let num = 10;
num = "abc";
Enter fullscreen mode Exit fullscreen mode

Not CS terms.

This is why I got mad at you. What makes you assert this? Take a look at the results in google:

https://www.google.com/search?sxsrf=ACYBGNQ7UX3Dc2VF-TcwYMPvKWARNQg2YA%3A1574698748299&ei=_P7bXavmEcKP0AaPw4TgCw&q=weak+vs+strong+typing&oq=Weak+vs+strong+ty&gs_l=psy-ab.3.0.0i20i263j0i22i30l9.4213.5245..6276...0.2..0.106.313.0j3......0....1..gws-wiz.......0i71j0i67j0.3V2-LF1mLSI

Not convinced?

https://www.google.com/search?tbm=bks&q=weak+vs+strong+typing

This will give you a number of results of books on compiler design that talks about the weak typing and strong typing. I hope this convinces you, for your sake.

Good luck.

Collapse
 
cubiclebuddha profile image
Cubicle Buddha

yeah, good luck trying to write enterprise node.js app without typescript

Absolutely. When you work at a large company where team members can be joining and leaving frequently... the only kind thing to do is to document your code so the next person can be productive. And since JSDocs can and often fall out of sync with reality, TypeScript always stays in sync.

I feel like the arguments against TypeScript are from people that plan on staying on a project. But if you have any interest in moving onto another project... how is the next guy going to know how your code works?

Collapse
 
rafalmaciejewski profile image
Rafał Maciejewski

I feel like the arguments against TypeScript are from people that plan on staying on a project.

I feel like that arguments are from people that are just writing small projects one after another and never had to do any refactoring or didn't even done enough bug-fixing in their career. Working with existing codebase written in TypeScript is by miles easier and clearer than working with codebase written in plain JavaScript.

Collapse
 
ms_35 profile image
ms

Typescript is not a panacea, it's just an extra tool in your toolbox. It's not meant to prevent all problems, just a specific subset of them. Think of it like syntax highlighting in your editor: no one is saying it'll make or break your project or that it's more important than code quality broadly speaking, it's just helpful.

I use Typescript for two main purposes:

  • Declare programmatically that I will never do something and rely on the computer to tell me when I do ("I will always pass an object that has a foo function that returns a string"). This is similar to linting and relies almost entirely on what you want to enforce. You can easily tell TS to leave you alone with any or you can be ultra specific { bla: (a: int, b (c: string) => boolean) => void }
  • Explore complex APIs more easily with auto-completion and type checking. The Apollo example is actually pretty good: Apollo tools have approximately 700 different options, with different types, etc. Not having to jump back to the documentation (or the source code itself) to know that it's addTypename and not includeTypename and that it's just a boolean and not a function is very helpful

I don't think you need to be at a large organization to get these benefits: you're always working with a gigantic codebase, either the browser or Node and probably at least one framework. You're also working with at least one of the most forgetful and error prone developer: yourself.

This article is very helpful about what exactly TS can help you with: css-tricks.com/types-or-tests-why-...

Collapse
 
curtisfenner profile image
Curtis Fenner

There's a few fundamental things I disagree with:

TypeScript is, by definition, longer than untyped JavaScript. As such, the development time is longer (assuming everything else is equal).

This is not true at all! That's because all JavaScript is valid, runnable TypeScript. Just run the TypeScript compiler on your code, and you have a linter that will catch some bugs and give you some hints in your IDE/text editor. This is already a great value, before you even change anything about the way you code.

In fact, this fundamentally means it can't be a waste of time because it doesn't require you to spend any time at all.

I genuinely don't find them more readable in most cases.

I would agree that the file without type annotations is more pleasant to read on its own (though I think at least some of the annotations could be inferred and so omitted). However, I am very very thankful for type annotations when I am opening up my 30th file today and don't have time to scour every line. While it might look like clutter while you're dissecting it, a) you have to do a whole lot less dissecting when you have types, and b) I don't spend time dissecting code all that often, I jump into something, get information, and move on. Types are a big part of that information.

And if clutter is a problem, this is an easily solved problem in your IDE -- just make it hide or make faint any type annotations that don't appear in JavaScript.

Typed JS is still... untyped.

The representation of values isn't relevant to types. C/C++ specify almost nothing about representation, and totally distinct types can be represented the same way.

Types are entirely about making static judgements from code. TypeScript lets you know things about your code before you run it. Sure, TypeScript isn't sound, but neither is Java. However, if you are frequently hitting problems because of unsoundness, that is a separate issue that would require a lot more details.

Collapse
 
dinsmoredesign profile image
Derek D

The biggest benefit of using a statically typed language is runtime type checks. Sending data to a server and it throwing an error because you forgot to change your string to a number is awesome. No extra boilerplate to cast a type to something you can work with is great, you enforce your users to send the correct data and if that data changes, you instantly know where the problem is.

TypeScript can't do this. TS only checks types at compile time. This can be useful during development in some cases, but I really question the skills of a developer who's constantly creating type errors in development, where you'd have to rely on a compiler to tell you your mishaps.

I would absolutely use TS if it had runtime checks, but without them, I find coding in TS verbose for very little payoff.

Collapse
 
stereobooster profile image
stereobooster • Edited

The biggest benefit of using a statically typed language is runtime type checks.

Read it outloud. Runtime checks e.g. dynamic type checking.

const validate (x) => {
  const i = parseFloat(x);
  return !isNaN(i);
}

Dynamic type checks are possible in dynamically typed languages.

Collapse
 
cubiclebuddha profile image
Cubicle Buddha

It does if you use ts-io

Collapse
 
patrickjh profile image
patrickjh

The key question is rather a 15% reduction in bugs is worth the time investment to implement typescript.

According to several sources I've seen (link for one at bottom), typescript and some other static typing systems achieve a 15% reduction in bugs.

Some math:

I have commonly read that software systems have 1.5 - 5.0 bugs per 100 lines of code.

This means a 1,000 line of code "small project" has roughly 15 - 50 bugs that need to be found. There are various methods for finding bugs, static type systems being only one way.

Mathematically finding 15% of bugs on a 1,000 line of code project means finding roughly 3 - 8 bugs.

In a vacuum this is good - until you factor in that there are alternative methods of finding the same bugs that take much less developer time than using typescript.

According to statistics in Code Complete by steve mcconnell, something as simple as personal desk checking of code catches between 20% and 60% of bugs in software. In fact, in comparison to most of the techniques presented in that book, a 15% reduction in bugs is mathematically one of the least effective methods. Code review, unit testing, beta testing and other methods all have higher percentages of bugs caught. Many of these methods take significantly less development time than using typescript, and end up catching the same bugs typescript would catch.

So on a small project of 1,000 lines my verdict is that typescript is not worth it.

However, that does not hold true once you consider larger projects. A project with 1,000,000 lines of code would statistically have between 15,000 and 50,000 bugs. On such a massive project with an equally massive team typescript would undoubtedly catch enough bugs to be helpful.

So the question is - where is the cutoff. I would argue - unscientifically - that a good rule of thumb is ~ 50,000 lines of code or 5+ coders on a team. Above this level the communication and bug catching benefits start outweighing the implementation costs. Below this level using a combination of other software quality practices (code review, unit tests, beta testing etc.) Will be able to catch most of the same bugs while being more efficient with developer time.

Just my preliminary thoughts, would be interested to hear other arguments.

google.com/amp/s/blog.acolyer.org/...

Collapse
 
cubiclebuddha profile image
Cubicle Buddha • Edited

Your citation (Gao et al., ICSE 2017) doesn’t consider if the repositories studied had code reviews / desk reviews. So the 15% bug saving might be after code reviews. That’s just one of many ways that particular study has been incorrectly applied. The study authors themselves point out that there are other benefits besides bug reduction.

That being said, I really appreciate that you analyzed the data and took a measured approach. That’s much better than this article we’re commenting on which by the authors own words is subjective. But hey, if people don’t like a specific tool, they don’t have to use it. But screws are hard to install with a wrench.

Collapse
 
patrickjh profile image
patrickjh

Thank you for your thoughtful response.

Collapse
 
bergermarko profile image
Marko Berger

Typescript is what JavaScript should have been.
I have been coding in Ts for 2.5 years. Just love it . It prevents (in some extent) junior developers to do stupid things.
Can't wait for Deno to become production ready.

Collapse
 
stojakovic99 profile image
Nikola Stojaković

Exactly. My current project is small e-commerce system and who knows how longer it would take me if I had to write everything in plain JS and how much more code I would have to use to validate input instead of just using class-validator.

Collapse
 
catchen profile image
Cat Chen

I worked at Facebook and I focused on driving down production uncaught error for a while. I would say Flow helped prevent a lot of potential error throwing code from being checked in.

All engineers in Facebook are full stack. That means many of them don’t know much about JavaScript but need to write JavaScript. When thousands of engineers from different teams writing JavaScript in a single repo and all the code interact with each other, bad things happen.

For example, one engineer calling function X expects it to accept nullable argument. He checks X’s implementation and it looks like so. He doesn’t filter out null when passing the argument. Everything works in his dev environment. In production, some branch in X calls function Y and some branch in Y calls function Z. Z doesn’t accept null but the argument is passed all the way from X to Z. A production error is thrown.

Why didn’t anybody realize this before the code was pushed to production? Because the authors of function X, Y and Z are all different engineers. The functions are in different files. The authors are from different teams. They never talk to each other. They happened to find a function in the codebase and it looked like the function can fulfill their need, so they called someone else’s function without checking thoroughly.

Flow helped a lot when you need to reuse someone else’s undocumented code as a blackbox. At least it’s a more reliable blackbox now. If you are building your own project and you only depend on well documented libraries, you might not have the problem Flow aims to solve.

Collapse
 
vimmer9 profile image
Damir Franusic • Edited

The everlasting problem of proper documentation. Totally agree. You should try Linux kernel stuff or syscalls, memory mapping, etc. It's all great but for the love of Open Source, somebody please keep the documentation up to date. I spent two days trying to find a bug in my own code when I finally realised that the issue was poorly documented sctp function. I looked around on mailing lists and all I could find was a single post complaining about the same problem. The final conclusion of that thread was that the man pages should be updated. Great, and who is going to do that and when? Anyway, I forked it, did it myself and created a pull request which was approved like instantly 😁

Collapse
 
yawaramin profile image
Yawar Amin

The Apollo Context code you cited is not exactly a shining example of clear and idiomatic TypeScript code (exported function return types should be annotated, and the defined interface type contains lots of object and any), however I would argue that it's still easier to read than the JS version. If you read the JavaScript version, can you tell at a glance what the context value contains and what you can do with it? It's dead simple in the TypeScript version.

Collapse
 
merott profile image
Merott Movahedi • Edited

I always recommend using TypeScript with strict mode on, while avoiding any at all costs. There will be cases where using any is unavoidable but even that can be kept under control with an extra layer of abstraction.

Once you do that, TypeScript will speed up your development multifold because you no longer have to worry about and fiddle around with silly errors. It also makes a lot of unit tests redundant.

Once you start to use any in your project, it becomes a waste of time. You might as well drop TypeScript and go with plain JS.

Collapse
 
nikpoltoratsky profile image
Nik Poltoratsky

from my point of view, the most beneficial parts of the typescript are following:

  1. Codebase research. Just imagine, you've been assigned to the project with 1 million lines of code. How much time it’ll take you to understand properly how it works without types?
  2. Code navigation. Again, if you have a large codebase, static typing simplifies codebase navigation.
  3. Refactoring. How hard is it to rename a number of variables without static typing?

Also, I want to mention that plain js without types is a good decision for a small project you’ll forget in a week about. While typescript can save you a lot of time in a long run.

Collapse
 
cmcnicholas profile image
Craig McNicholas

For me it comes down to readability, refactoring and robustness.

Readability - yes js Devs can read js code but my experience indicates that almost any Dev can read and understand TypeScript more completely.

Refactoring - largely IDE dependent but large codebases 100k + lines of code are a nightmare to refactor with raw JS. We're 18 months into Vue with TypeScript and I wouldn't look back.

Robustness - the depends on the makeup of your team but we have a mixture of very proficient JS developers and more general software engineer types. They all catch issues that only seasoned JS Devs spot due to the strictness of typescript at the point of writing code

Collapse
 
absohabsoh profile image
Nathanael Bennett

I just find enums, and in certain cases, interfaces, to be very helpful. For a large codebase, the value of being able to glance at code and understand what it does is very helpful. It's even more helpful because of the dynamically typed nature of Javascript. ONE + ONE could equal 2, or it could equal "11", or it could be undefined, or cause an error.

We're in the day and age where your IDE is your best weapon for producing quality code, and TypeScript keeps your JS IDE experience first class.

Collapse
 
sidhantpanda profile image
Sidhant Panda

This was quite the 'hot-take' on TypeScript. Lets go point by point

1: The pros aren't really pro
Big companies using it or not is a claim by people. Its got nothing to do with the language itself and as you rightly said, "Big companies also use legacy systems, therefore I should use legacy systems."
shouldn't be the reason to use it. With this you are fighting a mindset and not the language features themselves.

Why not just use Babel?
The following compiles with Babel:

const definitelyAString: string = 9;

The real pros is better code maintenance.

2: Typed JS is long and difficult to read.
This seems to really be a subjective one. I don't think I can change your mind about it. But a lot of us actually like the verbosity with interfaces to understand deeper into what all we can use and modify.

3: Typed JS is still... untyped.
As many others have pointed out, JS is not untyped, just dynamically typed. How does it matter how the variables are allocated in memory?

Adding interfaces and types to models is a one time affair. But the developer productivity post that is just incredible. Auto-complete shows all available members, and even description (if added as JSDoc comments). You will never run into a typo for accessing a data member from the model.

4. What's so bad about untyped JS?

  1. The time taken to add interfaces and types is time saved for anyone re-using that piece of code. So its a one time effort vs effort from multiple people multiple times.
  2. Seems to be true of any language. So it's neither a pro or a con?
  3. Seems to be a subjective one. So let's leave it be.
  4. You can't escape test cases in any language.

5. More importantly, look at design patterns and learn to spot code smells
Completely agree! This is true for any developer working on any kind of project.

Collapse
 
andrewbrown profile image
Andrew Brown 🇨🇦 • Edited

I use both TypeScript and Coffeescript.
Both have their utility.

When I wrote my open-source Tetris attack clone I ended up porting it from Coffeescript to TypeScript?Why? Because the joining developers had a really hard time walking into that codebase that was implicit. Switching to Typescript means you had to define all your Class properties so you knew what was going on in that class, even with weak typing, everything was more verbose.

When I set out to build my own javascript Framework DilithiumJs I decided to use Coffeescript? Why not Typescript? Because building web-apps is routine business, having a productive, concise language fits really well.

Collapse
 
normancarcamo profile image
Norman Enmanuel

You are one of mine's, I know what you felt on those interfaces, actually at the end of the day, we end-up adding more code, and more code is more job because one have to maintain it too and sometimes you have to create some extra layer just to maintain in control all what you're doing.

I think that we have to respect the nature of JS, I prefer to use the types on Scala or Haskell (Some languages that I work with) than simulating them in JS.

People used to think that JS is the problem, and I think that the main problem are de coders.

Collapse
 
bigredmonsteruk profile image
Big Red Monster

That's actually a good point.

Typescript uses a bad types system. Why couldn't they have done something more innovative along the lines of Haskell?

Collapse
 
huppopotamus profile image
huppopotamus • Edited

Agreed on all counts, though I think you could add another to your list. I've often heard that typescript is meant to aid developers who are familiar with object oriented languages learn to write front end code in terms they're already familiar with. Personally, I don't think typescript keeps you from having to learn JS or ES6 and how it functions and behaves.

Also, as you mentioned, for me, typescript hinders me more than it helps, and I've not yet found a situation where typescript provided me with anything at all that I couldn't already do myself in ES6 with some simple functions.

If it's up to me, typescript is a hard pass.

Collapse
 
guneyozsan profile image
Guney Ozsan

It feels faster to develop with static type checking because you can be more confident about what's going on. It's like driving on the highway, you burn more gas but can go much faster because your path is secured in advance.

Also IDE can assist you all the time. JS always feels like driving an off-road rally car without an assistant driving sitting on the seat next to you.

JS is awesome for small scripts that ease your daily activities but I wouldn't let my million dollar investment depend on it.

Collapse
 
calvintwr profile image
calvintwr

I think fundamentally, the extent of the discussions suggest we probably all agree that an argument has to be within what is intended for a function to handle.

Notice I wrote “within what is intended”, and not whether it is of the correct type. Type is only one dimension, fiercely focused upon, and I very much agree rightfully so. But could it have inadvertently cause other dimensions such as range —which is perhaps just as important — to be grossly overlooked. Perhaps more often than not, it’s the consequence of the latter that is so hard to debug. I illustrate:

(1) It is usually not just a matter of type, but also the range of value that your function can handle, e.g

function howManyDigitsInAnInteger(integer) {
    return parseInt(Math.log(integer))
}

The above function looks fine, but actually, integer has to be between 0 to 999999999999997 for the function to work! So this function has a limit before it starts going cranky. The problem is that function silently appears to work normally. A programmer might be alluded to think, “I have strict typing, things won’t go wrong”. But the range... we forgot about the range.
(Although you also have to check whether a proper integer was given, and not number with decimal point, but I think that’s one level above type and range checking. So that can be checked with some code within the function.)

And (2) in the world of JSON, everything is a string, so it’s most practical for a mathematical function to handle both Numbers and also strings that are actually numbers. So if we use the previous example, what you really need is a function that will throw error if the argument is not a string or an integer, is a string that cannot be converted to an integer, and/or the result of which is not within 0 to 999999999999997.

It was never just about type. Its about type, and range, and externality (knowing that the transport layer can mess up object typing).

A validation library comes close: github.com/sindresorhus/ow

But perhaps we all need to shift away from so doggedly fighting over whether to type or not to type, than to move one and recognise that it’s more that just type, and perhaps build something better for the future.

Collapse
 
jharrilim profile image
Joe

In my mind the number one point is, "do you work with data"? For me this is always the case. Database schemas are always are tightly bound contract. Knowing the shapes of your documents/entities/models/etc are important. There is never a time when I want to guess what the fields of a table/the properties of an object are.

Apart from the want for types, Typescript itself is an amazingly well designed piece of software. It's ability to express types that can actually translate fully into a dynamic language is amazing. It's option for strict checks seriously do help me write better code.

The refactoring support from Typescript is well noted, the VS Code support is fantastic, the ability to target multiple versions of Javascript with Typescript is very useful (not to say Babel isn't, using Babel with Typescript is also good), and the ability to read Typescript in my opinion is better.

I frequently read open source code on Github, and when I'm reading Javascript code, there isn't enough information for me to fully understand it. Typescript gives me a much better description of what I am reading.

Types are like adjectives; they are meant to describe things. Most of the time, I want to be able to clearly describe what is happening in my code, and I want the code that I read to be descriptive enough as well. Types are not a replacement for documentation, but I feel like they definitely need to both exist. Types not only help human users understand code better, but it also helps your tooling understand your code better.

Maybe I'm biased after using compiled statically typed languages for so long, but after using languages like Rust, C#, or Kotlin, I just feel like not having a proper type system is almost always bad when writing large projects that interact and describe a lot of data. I'm just going to document the types anyway; I might as well have just written it in the type signature.

Collapse
 
arvigeus profile image
Nikolay Stoynov

Not sure if you are genuinely frustrated with TS, or trying to make a point, or just making a clickbait article. I'll just comment on point 1, cause life is too short, and this will get buried anyway...
The reason big companies are using it is exactly the reason developers should learn it too. End of question. No matter if TS (or any lib) is pile of garbage, or The Holy Grail. It's the same reason people are still learning exotics like KOBOL and etc: if there is demand for it, better be prepared. "I'm sorry, I didn't learned TheNewHype.js because I didn't found a valid use case myself" is an admirable statement, but will get your CV in the trash on a job interview. Unless you are a project lead and you make the calls yourself. But then you better tried it before denouncing it. There is another thing: any lib is somewhat easy to learn, but always hard to master. Getting an experience prior, knowing tricks and pitfalls, is a huge boost.
Because of all listed reasons, now I am building and app with Redux. The app is too small, and this is practically an overkill. I don't quite like Redux myself. If it was my choice, I would go for something else. But this is what many companies use, rightfully or not, then I need this in my skillset.
Keep an open mind, and only engage in constructive discussions, not bashing ones. Your opinion won't change the world, but your input might help.

Collapse
 
stringparser profile image
Javier Carrillo Milla • Edited

I looove types! And I really hated them beforehand. As in really really really hating them.

It felt patronising. Like "who do you think you are computer I tell you what to do" patronising.

Now I apologize. Ok sorryyyy...

Even if with TypeScript is not really really really typing they help a lot with refactoring, auto-completion and gives you documentation on the spot from most libraries. So right there you have saved a lot of time changing from being looking at code to switch to browser and check docs.

"Oh, that's what this does. Ok let's see... that argument is not clear. Was the third argument a number or? Ah no, is the first... wait that is for the current version of the package I have? Let me see the package.json... oh great the documentation is only for the latest version. Ok let's update. Wait can I? Wait... what was I doing?"

So for me its totally worth it. Sometimes I browse methods even to see what the API does. It's greaaat!

🕺

Collapse
 
qheolet profile image
qheolet

I am open to read new opinions about TS but I read this articles and he do not get it. Business do not use just because they want to use it. TS give a bunch of tool that the enterprises point of view make the development more scalable, readable. The types and the interfaces and the TS insight give you more contexts and the intentions of the previous developer, one of the problem with JS is work with legacy code no well documented you need to expent a hard time just trying to understand the context and scale that code sometime was better to do from scratch.

Collapse
 
snowshoes profile image
snowshoes

I've been using TS for 2 years in both work and personal project. It still can't convince me as the "better" option for front-end dev, through the communities did a lot to improve JS development experience. Here are things difficult to tackle:

  1. Steep learning curve
    It's not quite easy for back-end programmer to totally understand some quirks in TS, not to mention the pure JS programmer. Personally I think its typing concept is more difficult than Java Generics. TS leverage the way people apply typing system to JS.

  2. Error prone typing
    How many times have you no idea of what's going on with the compile error. i.e. Variable foo implicitly has an 'any' type. Why don't you infer the type? It's not us but TS should do type inference ! It's on earth NOT TYPED language, even TS advocates it's better JS because of typing.

  3. Inefficiency
    Most of time the developer doesn't focus on their business but strive to satisfy TS compiler. In my case I have to at least spend 60% of my time in handling type issues in TS than to do the real job. I think most of the developers encounter such hassles, things get even worse when we need to browse github issues to resolve type incoherence. seems like I need to double my effect in resolving not only code but type error too.

  4. Alternatives
    Kotlin seems like a sound alternative to TS in JS development. It's eye-catching in the way how static typed language compiles into JS, even though it's not that seamlessly integrated compared to TS right now. But personally I would definitely switch to a static typed language to do all front-end dev once it becomes stable and convinced.

Collapse
 
aestheticsdata profile image
joe cool
Collapse
 
gatisnegribs profile image
Gatis Negribs • Edited

Totally agree that Typescript is waste of time and resources.
If you disagree change your mindset about coding - stop being chaotic and keep your code well organized. It will really level up You and your code, not the usage of Typescript. If you still disagree probably you are mostly backend developer, I would recommend then to learn Javascript more - JS is not so sensitive on data types and it is more easy to find and debug.
In any case, if you find Typescript helpfull and you are using it, probably your code still will be shity, because you are doing things wrong.

Collapse
 
mmikowski profile image
Michael S. Mikowski

Type management is enormously important in JS, but that doesn't mean you have to use TS and all its complexity. In my experience self documenting code is far more effective. See typecasting here - mmikowski.github.io/typecast-02/

Collapse
 
danielearwicker profile image
Daniel Earwicker • Edited

“TypeScript is, by definition, longer than untyped JavaScript. As such, the development time is longer (assuming everything else is equal).”

This is only true if you believe that the effort required to create software consists mainly of mashing the keyboard, i.e. dev cost equals number of characters typed in by human fingers.

Obviously that’s not how it works. We spend more time thinking than entering code in an editor. Quality is way more of an issue than quantity. Therefore consider the possibility that by writing down some extra helpful information, development effort can fall.

Your other conclusions related to catching bugs. This is not the true value of static typing.

Think of a modern IDE as an intelligent assistant. It can assist you more if you let it know your intentions. Objects in some situation are meant to have a certain shape, so let your tooling know this fact! Declare what you mean to be true.

Meanwhile, other people reading your code can use the type declarations as documentation - but it’s way better than comments because it is definitely up-to-date, whereas comments usually aren’t.

TS infers the majority of type information (this is how VS Code is able to be so helpful with plain JS - it uses TS behind the scenes). But the remaining gaps where a declaration is needed are well worth filling in. Why? Because you’re stating facts that aren’t explicitly stated anywhere else. Without stating them, you’re leaving a vague puzzle for the next maintainer to figure out.

You have to write tests when using statically typed languages, of course - unit testing is commonplace in Java, C# etc. But writing tests is easier when your IDE does some of the donkey work for you. Types make your editor more helpful. Help your IDE to help you. And help the next maintainer too.

(Sidenote: you’re misinformed about C/C++ - they provide no runtime type safety; raw memory is interpreted according to the assumed type, and so a JPEG might try to be read as a string, or even executed as code).

Collapse
 
gibbitz profile image
Paul Fox

JS is not statically typed for one practical reason, which is to allow for smaller file sizes (by not expecting annotations to be built into the interpreter and not delivered as part of the code). Remember this is a language designed to be schlepped over phone lines. From that standpoint, TS is a good idea in that it provides this largely developer used feature to the language.

The problem I have with with TS is it is a poorly designed programming language based on it's context. For example, when defining a type, unlike object literals in JS from the beginning, each property is separated by whitespace and not commas. When defining optional properties the operators used are very similar to ternary operators missing a truthy value in vanilla JS (variableName?: valueOrType) This adds to the cognitive load when reading the code slowing down developers and I would argue doing the exact opposite of what type systems are supposed to do for a language (make the code clearer to understand and thereby faster to read). What this does is allow environments to read the code and provide hinting, but I have to wonder why we can't have a more human readable option that does this. Actionscript 3 provided a type system annotation similar to Java that followed the syntax of Actionscript 2 without adding syntactic confusion, so it's not like designing a language that is strongly typed and consistent in style is impossible. It's unfortunate that the community has glommed onto the first thing that came along. I would hope that we use a more discerning eye than just checking that it works before we adopt conventions in the future.

Collapse
 
coin8086 profile image
Robert Zhang • Edited

At least I can say TypeScript is too complicated to read:

flatMap<T, R, O extends ObservableInput<any>>(project: (value: T, index: number) => O, resultSelector?: number | ((outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R), concurrent: number = Number.POSITIVE_INFINITY): OperatorFunction<T, ObservedValueOf<O> | R>

This is the definition of an operator of RxJS(rxjs-dev.firebaseapp.com/api/opera...). I can't believe I need to read it to understand what it really is in my daily work!

Collapse
 
alexmorleyfinch profile image
Alex

Point 2 all the way. It's the single most reason that I hate typescript. There are some cases where having types helps, and I get that... But most typescript enthusiasts want to use it everywhere, and that's where I take issue. It doesn't belong everywhere. It's not needed everywhere, and it's not applicable everywhere. Typescript purists are like old school socialists. They want people to use typescript whether they need it or not, fuck context. I say fuck typescript in 50% of cases. I think TS is most useful for entities and libraries.

Collapse
 
swiftninjapro profile image
SwiftNinjaPro

Personally, I think javascript is supposed to be a dynamic language, and typescript removes the dynamic type usage of javascript. I tried typescript at one point, and found setting the proper type difficult at times, and in some cases, impossible to do things a specific way. For making things easy to understand, just use common english words, or name parameters by type, ex: (str, obj, num, arr, bool, ect.)

JavaScript also hast "typeof" option you can use any time you may need a specific type. Also, for security, you can use typeof to verify user inputs, while typescript (which compiles to javascript), may cause a false sense of security.

Collapse
 
wlcdesigns profile image
wLc

I agree with this article. I'll add that TDD would eliminate most of the need for Typescript. On top of that, how many of your total errors are type related? I would really like to see how some of these Typescript dependent projects are written. I'm pretty sure there are layers of unnecessary complexity due to an insufficient understanding of javascript and compositional programming.

Collapse
 
wmertens profile image
Wout Mertens

Types are just a hack to give hints to your compiler.

A correct program is still correct without types.

Types are like drawing lines in the sand and saying "all values of this item lie within these lines". The typing system lets you define those lines with varying accuracy.

There are languages where you can say that a function will get arrays of length n and m, and it will return an array of length n+m. But why stop there? After all, each element could be an algebraic transform of the input, let's type number -> 2*number. It gets a bit silly imho.

In the end, types give information that code analysis should be able to get automatically. Given infinite time. Therefore, they are duplicate information, and should only be used where the compiler struggles.

I would be happy with mostly untyped TypeScript. In fact, that's what vscode already provides, thanks to context aware completion and typed libraries :)

The only thing I sometimes miss is something telling me I forgot to await a Promise (although sometimes that's exactly what I want to do).

Collapse
 
bigredmonsteruk profile image
Big Red Monster

"I would be happy with mostly untyped TypeScript. In fact, that's what vscode already provides, thanks to context aware completion and typed libraries :)"

untyped TypeScript? That would be ESNext surely? Except not as good because it wouldn't have the newer ES features and you'd have to have a compile step.
Also other IDEs provide context aware competion for plain JS (IntelliJ, Webstorm, Atom + tern)

Collapse
 
stereobooster profile image
stereobooster

I have response for

Types are just a hack to give hints to your compiler.

here (section Are types only required for the compiler?)

Collapse
 
bradymholt profile image
Brady Holt • Edited

Kudos for the constructive criticism here. I really like having these types of discussions about technical things because I feel like our craft has issues with mob-mentality and we all just jump on the bandwagon of adoption without fully considering a tool in the context of our environment.

Full disclosure: I'm a fan of TypeScript. IMHO TypeScript is one tool in a war chest and not a silver bullet. I think those that expect that TS will "fix all your JS problems at build time" will be disappointed. But, it certainly does catch some things at build time along with providing some fantastic dev tooling.

To some of your points:

  1. "you can just use Babel" re: older browsers and ESNext features but if TypeScript can do those things and others, it seems like you're killing 2 birds with one stone, right?
  2. "Typed JS is long and difficult to read" - sometimes, yes. TypeScript has gotten pretty good with implicit typing so it can infer the types and they don't have to explicitly defined. For example, if your function returns a string you could declare a variable with the result and it will be typed as a string (const foo = myStringFunction())...no foo:string needed. Anyway, verbosity in code doesn't really bother me.

The dev tooling is one of the most compelling things in my opinion. There is some effort involved in getting everything setup and avoiding :any for everything but I think it's worth that effort, especially for a larger project.

Recently I was building an app that used an API client library published on npm that had TypeScript definitions defined in it. I imported the module and started calling API endpoint method wrappers and the types clearly defined (and enforced) the shape of the request body and explained (and enforced) how I worked with the response data. If I was missing a require field, it was obvious. If I referred to a field that did not exist or was misspelled, it was obvious. This all felt very productive and helpful. It was all made possible because of TypeScript.

Collapse
 
desone profile image
Desone • Edited

Scripts are not languages. they are not compiled and they do not need types.
Interpretation like what happens in browsers for JavaScript like what happens for bash scripts or Perl, is different with compilation and this is why these scripts are there, Exactly!! For not being typed!
Agree with the contents. Typescript is completely unnecessary. It becomes a nightmare after you add it. Makes silly errors and attracts lots of effort and makes your development dramatically long and makes you non-productive. You can hardly get rid of it later because you will have to rewrite all your code.
And finally "typescript is not a super set of JavaScript".
Those who said it is JavaScript were simply, cheating!
The reality is once you write a class or component in typescript you'll find out that it cannot work with unconverted classes and non-typed objects through unfriendly error messages.

Collapse
 
gibbitz profile image
Paul Fox

Looking at example files from Angular ATM and seeing that they're using the TS extension and nearly none of the type checking and realizing that 90% of the TS code I've dealt with is this way. I agree that typed languages are great for documentation and predictability in codebases, but I find that these are not what TS is touted for.

Usually folks are preaching about how TS helps with Uncaught TypeError in the browser which is almost 100% caused by bad inputs at runtime (not compile time where the TS enforced type-checking happens) or with "finding (or fixing) bugs". From the simple fact that typing is optional in TS and that the buildsystem is enforcing it means there are many ways to hack around the safety that will be exploited by contractors because they are measured on speed and perception of efficiency, not quality or actual efficiency. Which leads to the perception of longer development times which is both true and false with TS.

At the feature level TS does increase development time. Adding a new feature that requires types and interfaces will take longer in TS than ES20XX it's more code, period. That said, TS will make refactoring or spinning up new developers on the project faster and will likely lead to more thoughtful architecture. If you come to development with the mind to rock out small features, then you get way more bang for your buck writing unit tests, but if you are looking to write a new site or platform you get a lot of future benefit from the blueprints provided by a strongly-typed TS codebase. The problems arise when feature teams start writing loosely typed code, neglecting to type or write interfaces. This is like the broken windows of uncle Bob mentioned elsewhere and it doesn't take long before there's a perception that the types are safe, but they really aren't. This is only compounded when non-technical types (or the inexperienced) get the idea that TS means your code is actually less prone to errors just by switching the "j" to a "t" in the file extension.

In the end this is why I prefer writing ES20XX, because I have no misgivings about whether it is type-safe -- it isn't. Then I can spend more time on unit testing and best practices and assume that there will be occasional issues with objects passed as arrays, numbers as strings etc. and look for the errors at runtime or in the unit testing.

Of course the fallout is in the design and onboarding phases and these now require more effort, but to be fair, it's a one-time cost. It's been my experience that business complains less about onboarding taking a few weeks than initial development taking a month or longer, so unfortunately there's no economic pressure to start a project right (using good type documentation).

I think a conversation like this one is aiming to say one is better than the other. If I'd have to side with one, it would be good ol' dynamic typed JS. Not because TS is a bad idea, but it runs into bad implementation every time I see it. I think what we need as a community is a better approach to dynamic types and better support of them in the tool chain. The thinking that dynamic types === bad and static types == good is not really the right thinking here. It's more like tooling for dynamic types === bad and tooling for static types == good. So instead of putting heaps of effort into writing better tools for dynamic typing we're making compiling a dynamic language from a newly invented static one. Why?

Collapse
 
akashkava profile image
Akash Kava

All arguments are applicable to one man army solutions, for teams, larger teams, forcing everyone to write better code by all other solutions you might have, does not work in reality, it creates chaos. I see lot of people want to label themselves as "Full stack developer" which is exactly "I am one man army, I don't work with teams", they usually isolate themselves in plain JS, functional only and many such technical jargon. Team consists of variety of people, everyone having different skills and different expertise.

Collapse
 
limal profile image
Łukasz Wolnik • Edited

Thank you, Lucas, for speaking up about this.

I came to JavaScript after working with C++ code for over a couple of years. And I had just fallen in love with the expresivness that JavaScript language provides.

I like the fact that I can choose whether I value static type checks more than I value the ability to write more code and then do the checks in different form of testings like unit-testing and end-to-end testing.

Collapse
 
imanmh profile image
Iman Mohamadi

I absolutely agree with you. I've been working with un-typed code bases for many years and I haven't had any issues. I think it's better for developers with minimum amount of experience. I will only use it if I want to publish a library that someone else will read and needs the types.

Collapse
 
saw_saw5 profile image
SAW

Doing types in JS just makes nerds feel like they are working with a more complex lower level programing language. If you want to waste your time doing it, knock yourself out!

Collapse
 
cybercussion profile image
Mark Statkus

I like me some Angular 11 but I just added a new checkbox via form control and due to the model, component, validator, service, html and a separate component for confirmation that one field went in 27 times! If anything its giving me so many more opportunities to screw that up before it let me build.

Collapse
 
tim92109_18 profile image
Tim Johns • Edited

I know this is 5 years old, but still a good article and still relevant in 2024. And still a popular argument. Just wanted to say, it depends on the person. For me, I never mistake my variables. I always know what type they are, and I've never had an issue refactoring quickly. If any of these don't apply to you, maybe use typescript. But I prefer to have cleaner looking, more readable, and faster-to-write code. So I prefer not using TS. I do use .tsx files, just in case something changes my mind, but for now I have not found enough pros to switch.

Collapse
 
ronbravo profile image
Ronald Bravo • Edited

Thanks for this post. I've been using vanilla JS since 2008 and can count on one hand the times I've had bugs due passing in the wrong data type or something like this. I came from a background of working in Actionscript 3.0 and Java so I was never opposed to types, it's just once I got used to Javascript I realized I didn't really need them. Once I got more and more into Mocha and really started loving unit testing over the typing kind of approach, but to each his own poison. I wonder if all the push for and popularity of Typescript is more around the increase of C# and Java devs doing more frontend work? Or maybe this is part of the popularity of Rust or similar languages? Personally, the only strong evidence I've seen for strongly typed languages has been optimization concerns, other than that it seems mainly a personal preference / comfort thing. I noted your article asked for hard data or empirical evidence, I would direct you to a few resources. My take away from these has been typically strongly typed languages don't offer much in terms of benefits along the lines that people advertise (with the exception of optimizations for compilers). Which then the follow up question becomes, is all the visual noise and overhead worth what seems little objective value (other than the subjective comfort) that the research seems to show? Some people have provided one or two counter papers in support of strong typing but even those papers seem to conclude the benefit is minimal or at least they were not able to measure anything as strong as what is usually advertised. In either case I support you and other providing a counter perspective against mindset that often is accepted due to culture and popularity rather a critical analysis and asking if it's always the right tool for the job? In the end I will leave you with a few articles and presentations that challenge the idea that strong types equals things like better refactoring, maintainability, security, scalability, etc. For you and others to enjoy:

  • The Unreasonable Effectiveness of Dynamic Typing for Practical Programs - This one is great because he actually cites empirical research done to investigate this question. He switch from being a strongly typed advocate to a dynamic. One thing I did not expect is that he explains how C++ is a language with the least defects for many of it's major projects. He credits this to the fact that many popular large projects (ex: Chrome) are built with it. So they in-directly gets robust usage and testing by the things used by these projects.
  • The broken promise of static typing - Makes great points about what people actually mean when they say strongly typed is better (aka less bugs) and does a soft analysis by reviewing a few github repos.
  • The Shocking Secret About Static Types - Eric Elliot also has no issue with strongly typed systems, his article is more of a critique around the strong claims of the benefits of Typescript and begins raising valid questions and points against it vs vanilla JS.
  • The TypeScript Tax
  • The Many Advantages of Dynamic Languages - A great summary of the advantages of Dynamics Languages
  • Rob Pike's OSCON 2010 keynote "Public Static Void" in 1080p, motivating the Go programming language - Rob Pike on the state of what is considered Industrial Programming. Note he is not advocating dynamically typed languages (which is why Go has types) he is admitting the problems with much of the verbose nature in which we are expressing programming solutions. It's more of a critique of OOP but really has relevance in the typed language discussion.
  • I spent 18 months rebuilding my algorithmic trading platform in Rust. I’m filled with regret. - A critique from a dev who built his app in Go (strongly typed) and then rebuilt in Rust (even stronger typed and focuses on memory safety)
  • Using Rust at a startup: A cautionary tale
  • Breaking Open: Erlang - Great talk with Joe Armstrong around the philosophy around the design of Eralng. He has great insights about the challenge of solving a complex problem without adding additional un-nessary complexity. I list Erlang because I think it has a key philosophy that is in contrast with a strongly typed mindset, which is that errors will happen. Period. Instead of building elaborate systems to try and prevent errors, create a system that can gracefully deal with errors and will allow the system to still run without crashing. This was an absolute necessity for their use case but I believe should have wider application outside of Erlang.
  • "Stop Writing Dead Programs" by Jack Rusher (Strange Loop 2022) - A great talk around how the constraints of computer hardware and philosophies of the past still influence the thinking around modern day languages, even though they don't need to.

And there's sooo much more out there. Thanks again for the post and take care. And before I get any hate about my response from others, please keep in mind I don't mind strongly type languages (C is actually one of my favorite languages), I just don't think they are necessary in all situations as some claim.

Collapse
 
cstroliadavis profile image
Chris

I feel like this article mostly reflects my own opinions on TypeScript.

In my experience, the main "pro" of TypeScript is to impose order intended to deal with the pain of undisciplined developers. JavaScript definitely gives you a lot of rope to hang yourself (and the rest of your team) with.

I've moved over to using TypeScript over the past few years and there are definitely some things that I like about it. For instance, IDEs being able to really know which interfaces you are using and give you better feedback about your code. Definitely very useful.

However, ...

My own experience has been that, as a disciplined developer, for every 5 minutes I gain with TypeScript, it cost me closer to 10 to get it.

With regards to being on a team of undisciplined developers. OMG. If you thought things were bad without TypeScript, just wait until you get undisciplined developers who are just trying to get stuff done with TypeScript. The result is type hell, and trying to do things "right" in that environment is way worse than in a similar JS environment, and that's really saying something.

I haven't used Flow, much, so I can't say if that's better, but I think if you're going to do TypeScript, you're going to need to do it in a way that is not so constrictive. It would be much better to have a really good and strongly enforced Peer Review process in place than it would to replace JS with TS, IMHO. It could simply be that the TS environments I've been in were configured to be overly strict.

I've found that I can fairly easily gain most of the benefits of TS with JSDoc comments, that most IDEs readily recognize. Obviously there isn't much enforcement of types, but again, it feels like the little gain I've seen there is offset by the cost.

Also, debuggers seem to work much better with straight JS than trying to interpret TS in mapped code. When debugging TS, I often find my debugger either ignoring breakpoints, or breaking in very odd places (essentially offset from my actual typescript code), and giving me information that is hard to understand or useless.

The one thing I can say for certain. I can definitely code much faster in straight JS than in TypeScript, and the way I code, it's much easier to fix in straight JS than in TS.

Collapse
 
luxcium profile image
Benjamin Vincent

TL;DR

I don't want to sound unconstructive [but I will]: I am already wasting my time in a love affaire with TypeScript therefore I will not try to convince you... if you have you reason (that are listed in the text I « ;dr ») then I will believe that they are valuable enough... Last time I read someone talking against TypeScript he completely missed the point (and I had to give my opinion there also)... it is because of him I « ;dr » you text... that is for sure a better argument than that other >>troll<<... For my part I am in love with that language so I do not think I could be convinced of anything wrong about it until something better comme to fill the same gap about JS... which I doubt will happen, at least not in my perspective... (fyi: I added your text on my reading list and will update my comment if I ever read it...)

EDIT: I am writing this edit and I didnt even yet published my comment... when I was about to go get the link for that >dude< I saw that post on medium that captured my attention...

  A Medium post ― Breaking Free of Javascript

Collapse
 
akmjenkins profile image
Adam

Good article and attempt at devil's advocate (that's what you were doing right?) One word rebuttal: intellisense.

To be fair, I've worked in several codebases that had such poor typescript usage I wished they were just JavaScript. Don't do typescript halfway (if you're casting stuff that isn't part of a third party library, you're definitely doing something wrong). This practice will put you further behind.

Collapse
 
captainn profile image
Kevin Newman

A "code length" measure of a language is pretty shallow. It also misses the point of what a static type system gets you, and what the trade offs actually are.

I will concede one point before I move on - some folks go WAY TOO FAR with static type definition, when they should be relying on more core model types, combined with as much inference as you can get away with. If you are writing types using every conceivable feature of Typescript, then you are just doing it wrong, and you are going to hate your types, and that seems to be where a lot of folks - especially library writers, who more often than not, completely over complicate their types. Maybe there's room for a book titled, "Typescript: The Good Parts" to clarify this point.

That said, what is a programming language? There are 3 components to a language:

  • Syntax - the actual written word. Something like coffeescript rearranges the syntax.
  • Static Environment - the aspect of the code that can be understood by reading the written code.
  • Dynamic Environment - the aspect of the code that is only determined at runtime - in JS that includes "types". They are there, but they are resolved in the dynamic environment, that makes javascript a dynamic language.

So what does Typescript add? In addition to a bit of syntax (type spec), it mostly adds a static type system, to the static environment, making it easier to reason about your code, and FAR easier to build helpful tools. JS has quite a bit in its static environment - you can tell the difference between a boolean, a number, an object definition, a class, function, etc. So it's not like it doesn't have types, but the only types that can be referenced in the static environment are those that can be inferred, and that doesn't include the shape of basically any object. The most notable place that breaks down is when you define function arguments. In that case, you end up with a blob - an "anything" type, for every argument, in every function, in the JS static environment.

Without Typescript, to understand what that argument is, and what it's receiving, you need to wait for the runtime - the dynamic environment - to run to that point, and resolve those types. If you like debuggers, or console.log, that's great, now you just have to run you program for each an every scenario that might call that function, and I guess hope no one calls that function from an unexpected location, with incorrect "anything" types (which is easy, because the tools we use can not have a clue what the correct types are for those arguments). You could read and test the function to make sure it behaves correctly with "correct" argument types, but that will not protect you against someone sending in "incorrect" argument types. In order to do that, you'll need to validate the arguments for the correct types - at runtime, which is more code, not less. Always check your inputs! (It's true that Typescript doesn't add type checking at runtime - we'll get to that.)

Typescript addressed that (and other scenarios beyond just the function) by adding the ability to specify a type for each argument. Now, you know exactly what type, what object shape, etc. about the type in your argument. This is a class of unit tests you no longer have to write. Even better, the build time type checker knows, and can tell you not just whether the internals of the function are correct, but also whether any caller of that function has sent in the correct variables, solving an entire class of common errors (no more can't access prop X of undefined), when used correctly.

That thing about a lack of runtime type checks - it's true, but because we can now resolve the types in the static environment, and prove type safety, we mostly don't need to worry about runtime type checks. But if we do need dynamic type checks (say if we want to expose your function to the world in an API, and need to validate inputs at runtime), we can use something like runtypes to translate our typescript types to runtime type checks - making that part where we need to validate your inputs at runtime a cinch.

Honestly, it provides so much benefit, and productivity gains, it's hard to take arguments against it seriously, except those that decry the over-complicated use by some but not all implementers. Yes, that needs to stop, but ditching types is absolutely bonkers to me.

Collapse
 
olafrv profile image
Olaf Reitmaier • Edited

typescriptlang.org/docs/handbook/t...
Duck typing is partially checking types allowing you to fool the concept of "type".

Also this article is funny too: dev.to/jfbrennan/the-reasons-i-don...

Collapse
 
judekeyser profile image
Judekeyser • Edited

Please consider this example, that shows typescript (and likely Flow) type system are not rich enough to be safe. They both miss the crucial points that JavaScript functions have arguments, return type, and invocation context, to be fully known (which would require dependent types, something that TypeScript does not have).

In particular, the following snippet is valid TypeScript, yet yields an undefined at runtime (no cast involved ; "compiles" also in strict mode):

type MyFunction = () => string;

class X {
    private me: string = "I know him, it's me";

    f() { return this.me; }
}

const x = new X();
const { f }: { f : MyFunction } = x;

console.log(x.f()); // Correct display
console.log(f()); // Incorrect display
Enter fullscreen mode Exit fullscreen mode

The language also badly supports prototype inheritance and re-patch.

TypeScript is not a super set of JavaScript, it does not follow idioms and constructions. What can be said I think, is that TypeScript syntactic rules are a super set of JavaScript ones (need confirmation). But as shown above, and what can be shown by playing a bit with prototypes, is that TypeScript type system is not strong enough to support JavaScript idioms and turn it 100% safe.

Collapse
 
maarlon1 profile image
Maarlon1 • Edited

I completely agree, a TS is a complete waste of time. It promotes bad programmers because it tries to catch their variable type 'errors' while every even average programmer knows how to check if a received data is of a right type.

Second mistake, TS tried to lure in OOP programmers making them to think that JS is a OOP strict-type language. It's not! It's a functional programming language with its own strengths and has an excellent object system on its own. Trying to make JS something it is not intended for - a big mistake. If we need an OOP, we should use an OOP language like C# or a C++

Third mistake, TS is clumsy, complicated and it's easy to write bad code that is hard to debug.

Fourth mistake, TS tries to correct only one error, wrong types while it doesn't cover tens of other user mistakes, like forgetting to insert closing parenthesis for example. Should we invent a new language for every possible erroror each?

Fifth mistake, TS compiles to a JS file which completely ignores all TS features and a resulting file is much larger than an ordinary js file, so it's inefficient. JS compilers, especially Google V8 engine has an excellent garbage collector that more efficiently allocates and frees dynamic variable type memory than 99% of programmers would be able thru efficient using of the right variable type.

There is more but let's end it here. Use TS if your employer strictly requires it (although they usually don't know why) and gives you a very good salary for it. Otherwise you may forget it completely

Collapse
 
firfi profile image
Igor Loskutov

With all respect to the author, I'm considering only the points/statements of the article.

I strongly disagree, partly because of how the pros/cons are presented.

First of all, the article title invites to a holywar, not to discussion. It's a strongly negative statement, probably in order to catch attention. Well, attention it got.

Secondly, the first point of the article already a strawman. At the first statement, it should be the biggest and the most impactful point, but instead I see fallacy. Who cares about "Big companies" (what specific companies author is talking about?) using this and that — we have our tools to do our job, in a maintainable, cheapest and fastest way possible. (I can elaborate on each point why Typescript achieves all of that, but it's not the format of a comment). "Big companies" use Java 1.6 and SOAP for god sake.

The second point says it doesn't appeal to authority fallacy and yet does the exact thing, additionally twisting it inside out. Indeed, the "authority" statement is about their personal preference about arrow functions but the author moves it onto types with ease. How's that even remotely related?

As to the core of the second point's statement, "typed js is hard to read", it's not clear if the author means any type system altogether as well (in which case it's another holywar topic where the counterpart would say "well untyped code is hard to debug") or is it only about Typescript type system only (then it completely lacks comparison with other languages and has to be dismissed as incomplete).

The third argument — since at the moment of this comment it's 2021 — there's a good example of the same logical circuit covid deniers use: "If masks/vaccines don't work 100% it means they don't work at all".

You stricten your code where it makes sense for business and leave JS where it doesn't. It's a great tool for accomodating to budget and requirements of your business, and to me it's strange to dismiss it as "it's all comes to untyped js anyways". Well, Rust code would all come down to untyped bytecode anyways, does it make its borrow system useless? Java generics would be erased at runtime but does it mean they don't catch bugs at compile time?

The 4th argument is a meme then a request for impossible at the moment — hard performance measurement for development teams. Except for the dreaded LoC measurement, which the author seem to regard in 4.1 as a benefit of untyped JS.

The 5th argument is a grain of truth and I can't disagree with that I know no one who would disagree. But it isn't related to benefits/shortcomings of typed js vs untyped js. You should structure your code well in both cases for sure.

I hope I got the points well enough and someone would find this useful for dismissing the concerns stated in this article.

Collapse
 
blujedis profile image
blujedis

When I hear this statement, please understand I'm neither knocking the author or those that agree with him, my first thought is always the same. This is spoken like a person that's never developed large scale enterprise applications. It todays world of rich UI's and their complexity, along with the multiple developers it takes to manage such a large effort, if you are not using Typescript then you are doing the client and yourself a disservice. At a bare minimum it makes complex refactoring simpler, it makes code more clear, and when working with large teams cuts down on needless "what does x do" chatter. While some of the gripes here are valid, in the end Typescript is a win for anything large, to scale or real.

Collapse
 
alexandreannic profile image
Alexandre Annic

You probably never had to do any refactoring on a large project to write something like this. TypeScript is just incredibly powerful, at least if you know how to play with it. For ever, it changes my coding experience and thanks to him, apps I build never crash on runtime anymore.

Collapse
 
acomito profile image
acomito

I personally spend way more time dealing with TS errors/issues then the time I've said when typescript alerts me of a missing parameter.

I'm also not at the point I can quickly parse a typescript file as quickly as I can a regular JS file... in some cases it's almost 50% more verbose file... I'm hoping if I can get some better syntax highlighting and use it in more projects that I'll eventually be a little faster with it but to date I'm not a huge fan.

Collapse
 
danjfletcher profile image
Dan Fletcher

For me it just comes down to refactoring, clarity and intellisense.

Being able to rename things and move things around the code base with confidence is almost enough of a reason for me alone. But clarity and intellisense are the big ones for me. I have to language hop a bit at my job and lately I get so frustrated in PHP or plain JS. I just can't stand having to source dive, or read documentation to figure out what a thing is or what's available to me.

Good names only go so far. When I'm inside a function, it's difficult to know what properties or methods are available to me on an object that's passed in as an argument without a type system. Plus I love being able to just type ctrl + space in VS Code and see a list of all the properties available to me. Especially when passing config objects 💖I can't stand figuring out what options are available without intellisense anymore it's just such a frustratingly slow and unproductive experience.

As for clarity, I think code readability can be very subjective and the longer you read a certain dialect the more you develop a familiarity biased. But I've always found strongly typed languages more readable than weakly typed ones albeit more verbose.

I genuinely believe I'm a more productive developer because of TS. I can read code faster thanks to being able to hover my mouse over a thing and see exactly what it's type is without having to open another file. I can write code much faster because when you use Types properly VS Code can auto-complete most of what you write. And I can refactor way faster because I'm no longer having to get smart about my find/replace.

Collapse
 
bigredmonsteruk profile image
Big Red Monster • Edited

As someone who has had to go through the process of removing Typescript from a large project (reasons below) I applaud some more discussion about this. Up until recently the TS community has been really vocal about their new shiny toy to the point I feel they are drowning out any naysayers and I think this is really unhealthy.

A few important things to ask any Typescript evangelist you meet:

  • Are they using "Strict Any" - Using TS without this is a really different experience to with it (and much more frustrating).
  • What kind of project are they maintaining? Sometimes the runtime is where you want to be iterating and Typescript gets in the way of that. Sometimes all you care about is making sure the code has every chance of being correct and typing may help you here.
  • Have they done much coding to modern ES6 standards (or even much Javascript at all)? - Many of the perceived benefits I see people lauding are just things copied from the latest ES standards. _ Which IDE do they use?_ This is _REALLY *_important. I had someone evangelise TS to me because they had been coding with Sublime Text and then switched to TS/VSCode. VSCode does zero JS intellisense so the TS completion is a pleasant surprise. Not to anyone who has been using an IDE that does exactly the same thing for JS (and has done for years) like IntelliJ.
  • Have they done much unit testing before? I really don't think the TS types system is remotely as usefuly as unit testing.

Reasons we removed Typescript (approx a year ago so things may have improved):

  • We have a pretty experienced team - we started to log when we got type errors. It was about once per developer per 6 months.
  • We have a project which is very look / feel / interface orientated so being programmatically "correct" didn't mean it was nice to use. Speed of Iterating on the runtime rather than the code is important to use. Having the Typescript build step got in the way. Having typescript at all made it very slow to experiment and user test changes.
  • Refactoring took ages and the types usually went out of the window - unit tests always saved us here - not TS.
  • Dealing with the non- TS world was painful - there was always friction between js libs and TS.
  • The compiler was a complete pain to set up when you wanted to do anything remotely "real world"
  • Speaking of the compiler - we had to run through Babel anyway as the TS one didn't always hit compatibility targets perfectly.
  • Libs we used had errors in typings files - usually being out of date. This problem occured more than we had type errors.
  • We were writing a lot more code with no perceived value and LOTS of added pain steps.
  • We have, as a team, been heading down the functional programming route and moving away from "classical OOP". TS seems to be built by people who want JS to be Java.

In short , my opinion:

  • If you aren't doing unit tests already, put effort into that before trying TS. (Jest is amazing)
  • Use ESNext and Babel it.
  • Use a good IDE for JS. IntelliJ, Webstorm or Atom with the Tern plugin are a good start. Maybe there are better VSCode plugins for JS now?
  • Try get into functional programming if you are still a "classes and inheritance" person. Lodash-fp is a nice starting point.
  • The future of Javascript is actually Javascript. Typescript is the new Coffeescript.

YMMV.

Collapse
 
foresthoffman profile image
Forest Hoffman • Edited

There is a certain point at which a codebase becomes too unwieldy to read easily regardless of what language or typing method is being used. We are all human. Humans are bound to make mistakes. The static typing provided by TypeScript allows developers to more easily create structured code to begin with. One of the largest drawbacks with JavaScript (which is also it's greatest strength) is how ambiguous it can be. TypeScript, like any other tool, empowers developers to be conscious of and follow strict design patterns in order to mitigate human error in the future.

As you inferred, TypeScript is a niche tool. Just like a ruler. You would use a ruler to measure things, cut cloth, and draw straight lines. However, a ruler wouldn't be useful for drawing curves or working with rounded shapes.

Collapse
 
siko279 profile image
Sijmen Koffeman

TypeScript is not just a language. It is tooling as well. You can use that tooling (like vs code does) and still write plain old js...

Development support and choice. Very valuable options.

And yes, when your code base starts to grow, TypeScript will prove itself. No doubt.

Collapse
 
emoranchel profile image
Eduardo Moranchel

Let me ask a question:
Should we try as a community reach a standard for bringing types to JS?
If the answer is yes, then TS is not a waste of time until we find a consensus all frameworks/languages/etc are welcome to try and push some standard.
For that reason I think TS is not a waste of time.

Collapse
 
bizzycola profile image
Bizzycola

I can't remember the exact differences(as I've not used regular JS in a little while) but one of the big things for me is I prefer how classes/interfaces/etc work in Typescript. But, of course, this just comes down to personal preference.

I do also like to be able to tell what a variable is just by looking at it, and autocomplete on types is pretty nice, but unfortunately, that only works if whatever you are using(JS libs, etc) actually has typescript definitions attached.

So yea, my main reasons for liking it are primarily based on personal preference.

Collapse
 
squidbe profile image
squidbe • Edited

When you said...

Do I believe that there are situations out there where TypeScript should be used?
Absolutely!

...you basically ended the article there. I'm not a big TS fan, but it does have its uses.

<tangent>
What's interesting to me is how Hungarian Notation seems to have fallen out of favor. It's a very simple way of letting devs know what type a variable should be. Yes, it doesn't change the way vanilla JS handles type errors, but from a practical perspective, when there's not a clear payoff to the added time and cognitive load of using TS, HN can be an extremely simple way to minimize the likelihood of type errors by clarifying the appropriate type, e.g., strFoo, intBar, arrBaz, etc.
Ah, the good ol' days. :-)
</tangent>

Collapse
 
calvintwr profile image
calvintwr • Edited

I think fundamentally, the extent of the discussions suggest we probably all agree that an argument has to be within what is intended for a function to handle.

Notice I wrote “within what is intended”, and not whether it is of the correct type. Type is only one dimension, fiercely focused upon, and I very much agree rightfully so. But could it have inadvertently cause other dimensions such as range —which is perhaps just as important — to be grossly overlooked. Perhaps more often than not, it’s the consequence of the latter that is so hard to debug. I illustrate:

(1) It is usually not just a matter of type, but also the range of value that your function can handle, e.g

function howManyDigitsInAnInteger(integer) {
    return parseInt(Math.log(integer))
}

The above function looks fine, but actually, integer has to be between 0 to 999999999999997 for the function to work! So this function has a limit before it starts going cranky. The problem is that function silently appears to work normally. A programmer might be alluded to think, “I have strict typing, things won’t go wrong”. But the range... we forgot about the range.
(Although you also have to check whether a proper integer was given, and not number with decimal point, but I think that’s one level above type and range checking. So that can be checked with some code within the function.)

And (2) in the world of JSON, everything is a string, so it’s most practical for a mathematical function to handle both Numbers and also strings that are actually numbers. So if we use the previous example, what you really need is a function that will throw error if the argument is not a string or an integer, is a string that cannot be converted to an integer, and/or the result of which is not within 0 to 999999999999997.

It was never just about type. Its about type, and range, and externality (knowing that the transport layer can mess up object typing).

A validation library comes close: github.com/sindresorhus/ow

But perhaps we all need to shift away from so doggedly fighting over whether to type or not to type, than to move one and recognise that it’s more that just type, and perhaps build something better for the future.

Collapse
 
cullophid profile image
Andreas Møller

The problem with talking about readability is that it's almost entirely subjective. You can often replace readable with "familiar". In your example however the Js version leaves out the most important information. The only part that's relevant when using your context wrapper. what does the context look like.

The difference between the Js and the typescript version is literally all the important information.

Collapse
 
aldoshin profile image
Aldo Perez

Is interesting discussion, and as many other things/topics in software development I think it depends on the needs. My early year as developer were spent writing code in static typed languages, mostly Java, whene I learned about languages like JavaScript and Ruby I loved the idea of forgot about all that verbosity. I really love you don't have to declare every type, or even think about if it should be a float or a int.
On the other side for big codebases I think having stricter rules and also having insights of what a function receives and returns is important for long lasting software. No many programmers last 10 years+ in the same project, specially the better ones. Typescript is in the same range as unit test, should you spend time on it? Maybe for lo lasting software it worths.

Thanks for sharing your thoughts

Collapse
 
th3n00bc0d3r profile image
Muhammad

I personally think, language shouldnt be a barrier, it should be more how you apply your skill, to maximize the productivity and minimize the time in which you deploy it.

Humans have languages too, and its purpose is to communicate, some people communicate in one more efficiently than other, which does not identify that one is superior to the other.

Collapse
 
johhansantana profile image
Johhan Santana

I’ve used typescript for a while now and I think it’s best used for open source libraries. For internal or personal projects I think it’s fine using JSdoc for documenting your variables and functions, in fact, most IDEs will give you hints when you use the JSdoc syntax.

Other things that I’ve encountered using typescript is sometimes you may have to do some workaround to get something to work when if you would’ve used plain JavaScript it would’ve been much easier.

For now I think JSdoc is enough.

Collapse
 
cullophid profile image
Andreas Møller

This article can really be summed up as

"real developers don't need typescript".

This same pattern can be seen every time new languages or Dev tools come out. Some subset of the more experienced community will automatically criticize it.
Bob Martin tells a story about how assembly developers were using the exact same argument when c came out.

"You don't need looping statements any experienced developer can use go-to."

Because typescript is an incredibly disruptive technology it will of cause have the same effect.

I have personally gone through the same cycle several times, most recently with prettier. If I remember correctly my arguments was:

"Something something something less readable"

Collapse
 
marcelgeo profile image
MarcelGeo

I like TS. You can pair your types with similar in backend application (Spring Boot ... ). Every developer now, what is coming from server. Therefore TS is fine in describing JSON data. In intelisense (VS Code) you have direct access and error messages for specified types.

I dont like TS. It is not solution for undefined issues, you must write sh.ts like checks for undefined. This is JS, no types like in Java, C#. TS is for me only good linter. Layer between developer and JS.

Developers must now, if is it important or not.

Collapse
 
ksaaskil profile image
Kimmo Sääskilahti • Edited

Thanks for the article, it was an interesting read! I won't say anything about TS, but I'd like to say that personally I would not like to see dev.to become a place where people hunt clicks to their articles with highly provocative titles and encourage people to endless flamewars. There's Medium already for that. I'm sure this article could have been written and its title chosen in a more constructive manner.

Collapse
 
josephthecoder profile image
Joseph Stevens

Well, for one. The tooling around Typescript is really good. Second, errors that would normally be caught at runtime are caught at compile time.

But I also agree with a few points there, typed Js still isn't typed. I think Typescript went for a middle ground approach in typical Microsoft style. I'm pro type systems, but the any type grinds my gears.

Collapse
 
atonchev profile image
a-tonchev

Totally agree,

TypeScript will be good only for:

  • Programmers who are very used stricktly to use types from other languages

  • Young programmers (That can let slide small type errors and mistakes, because they did not test their own code) And I think this is the reason big companies use it.

For everything else - big NO

Collapse
 
desone profile image
Desone • Edited

Typescript is JavaScript annotated for better machine readability at the expense of human readability and productivity.
It is recommended by big techs writing code linting and code assessment tools.
Actual product companies must be careful when they listen to advise coming from cloud providers and tech vendors.
Yes , they have good technical expertise, but their formula/equations of loss/profit is different and their profit might be causing you more expense.

Collapse
 
gardner profile image
Gardner Bickford

TypeScript is, by definition, longer than untyped JavaScript. As such, the development time is longer (assuming everything else is equal).

Everything else is not equal. The cost of finding bugs later in the SDLC is demonstrably more expensive than finding them earlier.

You allude to the fact that TypeScript is unnecessary for experienced programmers which leads me to believe that you agree it's helpful for inexperienced programmers. You work for a place that produces inexperienced programmers.

Collapse
 
eromanowski profile image
Eric • Edited

In flexibility: Typescript > Flow
In strictness + dev time: Flow > Typescript
In an untyped world in dev time : Untyped > Typescript > Flow

Flow may cost the most up front, but having true enforced type checking across the code base will drive out more bugs and reduce dev time significantly.

Typescript is optional, but can achieve the same type checking goal without having to implement it throughout the entire code base. Typescript is just a tool you can integrate throughout your code base. You can optionally run your JavaScript through a TypeScript compiler and it will help you find bugs in the code.

I'm a firm believer that if code is part of your core business, all data types need to be strictly defined. When using Typescript, the use of any or other generic types is frowned upon.

Untyped is the wild west. When you have no guarantees on data types (i.e. ), there are no more guarantees when the owner changes their data types, its consumers will remember to change their code as well. The hidden cost to this is that consumers are not made aware of the breaking change. So they will have to find it runtime with numerous hot fixes for each consumer.

When you run into a data type issue, typically a null reference exception, it can potentially take hours to debug. As that data flows through the systems, its value can be mutated and changed. When it arrives to your system, you have no idea whether it is a collection or primitive by looking at the variable. You have to run it to verify that it is truly a collection or primitive. If the provider of that data changes it, you can setup a shared data contract with your consumers, letting them know when types change or new versions become available.

My firm stance: There must be an agreed upon contract with data types if you are writing enterprise level code.

Collapse
 
ohscee profile image
Vincent S.C. • Edited

If I had to summarize my preference for using typescript succinctly: it's quite simply easier to pick up a project that has been written with typescript, and I mean that in the sense of IDE autofills. I'm a vim user, but I have to assume other IDE's behave the same way. It's nice to work with predefined objects made by other people and not have to go on a goose hunt to find expected values -everything is right there for your autocompletion, definition showing... etc. pleasure.
And maybe I'm a bit old fashion, but I find merit in taking the time to define enums and interfaces, beyond my own satisfaction of doing so.

Collapse
 
fwd079 profile image
Fawad

TypeScript is not for people from front-end/JS background.

It's for people with OOP background, people like me, who are from ASP.NET / .NET Windows community and wanted to break into Angular/Core etc. People with extensive Type/OOP knowledge absolutely adore it. Makes JS a breeze.

Regards.

Collapse
 
mojo2012 profile image
Matti

I think your argumentation has some serious flaws :-D:

my Sequelize database models was over 5000 lines long on its own
I know this is common in JS land, but in languages like java it is actually discouraged to use files with so much content, especially interfaces and classes.
Everything "entity" (class, interface) should be in it's own file imho, named after the entity's name + .extension.

If your function is actually not defining a return type, defining this type/interface is useless, I give you that. But you should actually define the return type! Then your IDE can assist you at the call site with some contextual help.

If you are the sole maintainer of a codebase, 60000 loc might be possible to handle. If you are in a team of >5, it's not (except you are clones and think exactly the same way ...).

Collapse
 
sabasayer profile image
sabasayer

Thanks for this post ,

Main reason we decided to use Typescript was ,we are building heavily business dependant project that has hundreds of api endpoints and data interfaces more than that .

We needed to create interfaces of models at the api so that we dont try to remember properties of every single model .

For small projects if you dont have restrictive types you dont need to work with Typescript. But if you are working with different types of data , it is a must for me.

Collapse
 
pdescham49 profile image
Paul Deschamps

The entire debate around TS v.s. JS IMHO will go on forever. it's like that dress that some people saw it as blue and others saw it as gold.

There will always be someone who looks at JavaScript and it makes the hairs on the backs of their necks shoot up because it lacks strong types like JAVA.

People who use strong typed languages day to day get used to that definition being there and they get comfortable with with it, If you take that away..... OMG the sky is falling..

And now for the people who don't use strong typed languages get used to creating a little bit of extra code making sure that some Array isn't an object or a string is not an array. Just a splash of code here and there. and POOF you don't really need this extra "typings" thing at all.

Now they are freaking out because TypeScript is making them write extra code and interfaces.

I am not going to root for either side. Again I think the dress is both blue and gold.

I will say.. Being an older dev who worked with a team in the "BROWSER WARS" years debugging a ton of JavaScript intensive slippy mapping applications (pre google maps) in IE 5-6-7-8-10-11.

We have come a long way. I "sometimes" like typescript. simply for VSCode's interaction. that is it. it makes JavaScript in an IDE behave like I am looking at JAVA. ;) navigating structures listing attributes etc.

I could easily go back to JS living in chrome debugger. walking objects.

I like them both and sometimes when I am making an interface in TS that frusterates me because I don't need to do that in JS I try anyway.. and If the JS Structure really can not be created as a Typing.

i use ':any' because it's all JavaScript / ecmaScript and that's still pretty awesome IMHO.

Collapse
 
worc profile image
worc

a new one i've run into lately: typescript is bad at building URLs. typescript doesn't have the flexibility you need to coerce data types back down to a plain string (sometimes with missing values!). and if you start re-adding that flexibility, it's hard to see the benefit of a highly abstract, obtuse type system, when you could just use plain javascript.

Collapse
 
tclain profile image
Timothée Clain

Nice wrapup ! Typescript fan over here but it is interesting to confront different opinions.

As for me, I consider typescript as a standardized way to give my IDE the information on my code.

As a library author in my company, I use typescript heavily in reusable code to give my collegues a "dropdown-driven development" experience. My goal is to make my peers more efficient and some advanced types help to deliver auto-completable, auto-validated libraries.

Coupled with a strong testing strategy, I found it very useful for refactoring.

Typescript take the direction to understand better and better javascript as well, so I suspect that at some point, typescript will be the inference engine for javascript ever and everyone will benefit from it.

Collapse
 
swiftninjapro profile image
SwiftNinjaPro

Personally, I think javascript is supposed to be a dynamic language, and typescript removes the dynamic type usage of javascript. I tried typescript at one point, and found setting the proper type difficult at times, and in some cases, impossible to do things a specific way. For making things easy to understand, just use common english words, or name parameters by type, ex: (str, obj, num, arr, bool, ect.)

JavaScript also hast "typeof" option you can use any time you may need a specific type. Also, for security, you can use typeof to verify user inputs, while typescript (which compiles to javascript), may cause a false sense of security.

JavaScript is a considered a weird language, because it isn't like other languages. I have aspergers syndrome (high functioning autism), so I might be considered weird because I don't socialize the same way as most people. Some people have noticed an advantage of aspergers syndrome in coding, because you don't follow typical standards strictly. I think creativity is important in coding. The standards might say, you should do it this way, but that doesn't mean there always right. You don't always have to copy the rest of the world, to inventive something new. If your coding, and your not creating something new, than I can see standards being helpful for building improved performance, if you were just trying to reinvent the wheel with better grip. what if the standards long ago said, every invention should be square. Then what if the inventor of the wheel followed that standard. Sometimes standards can help, but sometimes you may have to ignore a few of them for your project to work properly.

If that last paragraph makes no sense, read its second sentence. aspergers includes a tendency to change the topic a lot. I did that by accident.

Collapse
 
murjam profile image
Mikk Mangus • Edited

I like some of your points. I can give you an example of why it is actually quicker to write.

I used to be a Java developer for years, recently (for a year and a half) I have been every-day writing Javascript/Typescript. And I have to tell you I still write Java a lot faster than Javascript. How come? Well, the magic word here is IDE.

When I write statically typed languages, I get a lot better IDE support and there is almost nothing that I write by hand. The easiest samples are moving/renaming some code or just importing something else - in Java/Typescript you do not need to worry, just make the move. With plain Javascript at least I haven't found a good setup for either VScode nor IntelliJ IDEA that would make these changes automatically for me.

Collapse
 
bigredmonsteruk profile image
Big Red Monster

Hey Mikk. I have found that intelliJ does a really great job if you are using ES6 modules. The second you end up using globals (sadly forced sometimes due to libs) then it's not as good.

Collapse
 
luciunknown profile image
Luciano Cardoso

When developers only had worked with JAVA, C#, DELPHI and others strongly typed languages Typescript seems the pretty familiar and the natural path. In Other words the only pro is that Typescript prevents developers to deal with paradigm shift that Javascript promotes.Google are pushing unused languages/tec through interesting frameworks like Dart on Flutter.

Collapse
 
zuhairnaq profile image
Zuhair

What alternative do you propose for static analysis in JavaScript? Or you're throwing static analysis out as well coz you're a genius savant that can predict the exact run time behaviour of his code across platforms and devices?

Collapse
 
tvicpe profile image
tv

To me sounds like a FB politician which don't want to accept progress.
First of all - your examples related to react: Typescript and React were never friends. It's a pitty to include arguments based on that!
Second, enjoy and think about why all new features are coming from TS to ES: jaxenter.com/ryan-dahl-fixing-node...

Collapse
 
antonio_sorrentini profile image
Antonio Sorrentini

For me it's all about the IDE. If the IDE you are using is really smart with a statically typed language I feel 75% more productive, speed and error free than with a dynamic type language. And yes, I agree these are not things you notice when writing 60 k ~ 40 k LOC software, but enter the 1 or more million of LOC realms and believe me you would remove this post. ;)
And that's talking of code written by my self. The real nightmare begins when you have to change/mantain the code written by others. For example 1 or more million of LOC written by some people you cannot even talk to because they are not in the team anymore. Those are the cases when even if I should choose that work or to be unemployed, I would strongly prefear to be unemployed.

Collapse
 
shailennaidoo profile image
Shailen Naidoo

I agree with a majority of your article, I feel that TypeScript's existence is largely just marketing. If you want a truly statically typed language then go for that but trying to treat TS as if it were a truly statically typed language then you are going to bump your head. It is only type checking at compile time and not runtime.

Collapse
 
mmendescortes profile image
Mateus Mendes Côrtes

I'm sorry, but I totally agree with your post!

Collapse
 
htondkar profile image
Hamid Tondkar

I don't intend to be mean, but the level of stupidity and naiveness of this article and it's author is hurting my brain.

Collapse
 
akashkava profile image
Akash Kava

Clever marketing trick !! This post is just trying to get all attention from every developer who have used typescript and love typescript.

Collapse
 
edgarwilsonroial profile image
edgarwilsonroial

Typescript IMO is just a nuisance. Another attempt of Microsoft to maintain influence in the dev.

Collapse
 
leodutra profile image
Leonardo Dutra

Just saying.

Collapse
 
benjaminapetersen profile image
Ben Petersen

Refactoring large projects.

This is the biggest value with types IMHO that isn't discussed thoroughly in this article. Having done some large refactors in several languages, the ones I have done in strongly typed languages have been far better experiences. Having a compiler double-check all your work is fantastic.

Otherwise, I agree, the initial code-writing stage is slower and time-consuming compared to JavaScript. I don't believe you write TypeScript to improve the initial code writing. You write it because you are working on a big system that you will have to change over time.

Collapse
 
lid6j86 profile image
Dave Torrey

Here's my personal modern opinion on the matter: I've used Typescript in the past, and I thought it was -ok-, but I think that modern ECMAScript has come a really long way to improve the weakest parts of native Javascript.

The gap between what Javascript natively allows and what Typescript offers has been increasingly narrowing - to the point that modern Js even offers things like private properties (I'll admit, the protected accessor is nice and missing from Js), decorators are in Stage 3, a much better integrated module system, improved scoping, an option between modern class syntax or the traditional function prototyping, symbols, destructuring, await/async, spread operators, etc...

When Typescript first started out, pretty much none of this existed. The one great thing about Typescript is that it's heavily influenced the direction that ECMAScript has gone. However, I'm of the growing opinion that the currently existing shortfalls have shrunk to a degree that I find it often much better to just be able to open up a file and start coding without worrying about any sort of transpiling. Even babel has slowly become less necessary unless you want the absolute latest features.

The typescript support in editors like VS Code and JetBrains tools often works just as well with Javascript if you're willing to put in just a little extra time to use JSDocs. Additionally, things like tuples are on their way to native support in Javascript

There was a time that I thought Typescript was probably essential. It has some pretty useful features, no doubt. but these days I find myself more and more wondering how much is necessary given how much Javascript has improved

Collapse
 
moeiscool profile image
Moe • Edited

good stuff man! I always thought TypeScript was a little dumb. I am glad you took the time to tell us its dumb in an educated way. thank you

Collapse
 
victorhazbun profile image
Victor Hazbun

All you need is JS, there is no reason to waste time learning TS.

Collapse
 
neurosys profile image
neuro sys • Edited

In truly statically typed languages such as C and C++, different variable types are stored differently in memory. This means that it is very difficult, borderline impossible to accidentally store data of the wrong type in a variable.

This is not correct for C, there's no run-time information about types in C, and you are allowed to write anything anywhere in process memory. Lack thereof is one of the reasons why it performs faster than those with runtime checks.

As for readability. It is harder to read a piece of text when it contains more information, but it is easier to understand the meaning. Pure JS may seem easy to read, but it's because it's lacking information that is often useful to understand the code.

JavaScript is similar in its success as much as BASIC was in 80s, I think, it allowed more people to learn programming. But it's not necessarily the best way to be effective and manage complexity.

Collapse
 
dman777 profile image
Darin Hensley

I completely agree with you. A person shouldn't write compiler language for a interpreter. Typescript is just internet hype and it will go away in time.

Collapse
 
bhgsbatista profile image
Samuel Batista

You opened up a can of worms here lol.

Collapse
 
gsouf profile image
Soufiane Ghzal • Edited

Want to do strongly typed web? Go with rust, compile to wasm. End of the discussion 🤷‍♂️

Collapse
 
solovieff profile image
andrey

Same thoughts here. Third try -- no time savings, but lots of library and config pains.

Collapse
 
xowap profile image
Rémy 🤖

But how do you scale? 😱😱😱😱😱😱

Collapse
 
tetthys profile image
tetthys • Edited

That's why I don't use typescript for frontend projects 👏👏👏 And I will drop typescript soon for backend. People use typescript because others use it without something reasonable.

Collapse
 
nobsob profile image
NobSob

Overloading to the CPU 98% is very bad for your computer.

Collapse
 
llyys profile image
Lauri Lüüs

Im my book, these arguments that TypeScript is a waste of time are sloppy developer arguments...

Collapse
 
toffee_coin profile image
Elijah Lucian

if you don't want to learn, I don't want to waste my time trying to change your mind.

Collapse
 
mohaalak profile image
Mohammad Hadi Aliakbar

work on a js project for 3 years with a team after that you know how typescript can save your time.
if only we stated using typescript early on.

Collapse
 
wrongrook profile image
Tim

Once a language becomes popular enough and starts to be used at "enterprise" level people start trying to turn it into Java/C#. I've seen this happen over and over again.

Collapse
 
charlyjazz profile image
Carlos Azuaje

I agree.

Collapse
 
jonrandy profile image
Jon Randy 🎖️

I won't try to change your mind. I agree 100%

Collapse
 
adisreyaj profile image
Adithya Sreyaj

I really think people love using TypeScript for one reason or the other... otherwise it wouldn't be on the top 3 most loved languages on the StackOverflow Developer Survey 2019.

Collapse
 
danivijay profile image
Dani Vijay
Collapse
 
ibnyusrat profile image
Muhammad bin Yusrat

Why would someone want to change your mind, by the way?

Collapse
 
etampro profile image
Edward Tam

Okay?

Collapse
 
cheston profile image
Cheston

this is some JUICY discussion!
Good post Lucas!

Collapse
 
bigredmonsteruk profile image
Big Red Monster

People have done this many times without TS. This is a provable.
If you want to push TS then I think this is quite a stale argument if you don't mind me saying.

Collapse
 
otolone profile image
Otolone

As someone who has spent time learning C++, I found JS unusual. TypeScript saved the day for me because I could eliminate errors very early on.

Collapse
 
codefinity profile image
Manav Misra

Very fair points. I have considered these my dang self, but just snuffed out those 💭 thoughts! :)

Collapse
 
juliang profile image
Julian Garamendy

I completely disagree.
IMHO this article is very subjective. It mentions 'fallacies', and yet it's mostly a straw-man argument. Especially the first and second points.

 
vimmer9 profile image
Damir Franusic

I agree, it's a very dangerous language and not everybody.

Collapse
 
quirkles profile image
Alex Quirk

Imagine dropping a reference to Steven Crowder and an npc meme in an article you wanted people to actually read.

Collapse
 
velociwabbit profile image
velociwabbit

Lucas I could not agree more.

Typescript is basically training wheels for java developers who have been forced to try and become competent in javascript.

Collapse
 
jafstar profile image
Jafar

I agree with the criticisms of TS, and would prefer something like Reason or Dart if I wanted real type checking.

I check prop types which gives me about the same amount of confidence TS would.

Collapse
 
ddemydenko profile image
ddemydenko

all right said
ts is a good thing overall, but you need to keep an eye out to avoid over-engineering and misapplication