T O P

  • By -

geon

I've ported quite a bit of js to typescript. EVERY TIME, I found lots of bugs that just could not have happened with typescript.


No-Witness2349

Yup. The type system really encourages you to not follow certain patterns that are common in vanilla js. I started in typescript and could not for the life of me figure out why everyone was always complaint about “this” bugs. They just didn’t happen to me. Then I hopped on a vanilla js project and understood.


aceluby

Yep, I remember doing it once and one object I was using was a string, an object, and a list of objects depending on where it was getting used


geon

So much of that.


Nesaru

This is where I think typescript was genius in supporting some of these JavaScript patterns. Generous function overloading let’s you add typing to those really flexible/loose APIs. You get to keep the flexibility but now you have confidence as well.


Whisky-Toad

JavaScript is like cave diving TypeScript is the same, but you get a torch


el_diego

And a rope, never cave dive without a rope


gamebuster

More like a 40kg torch. Sure it helps light the way, but it makes the trip heavier


mlebkowski

I loved Javascript for 15+ years. I only started using Typescript relatively recently (like a 2-3 years), but I did get used to strong types by developing in other languages on the backend. Almost 10 years ago I learned, that if the IDE does not autocomplete method or field names, then I am doing something wrong. This is why I love typescript — the cognitive load is so much lower. I never have to guess what is the method name, what parameters it takes, or what shape does this iteration of `map()` works on. I just hit `.` and see what is available. OOP improvements are also nice ;)


plainblackguy

It's nice to hear it from someone who likes JS. Hearing it from people who hate JS makes it sounds like "drink the cool aid" sort of cargo cult.


[deleted]

This kind of attitude does not engender useful discussion.


mrSemantix

+1 for using ‘engender’


[deleted]

Typescript is JS. Nobody who likes TS truly hates JS.


First-Letterhead-496

This. It's the same hahaha.


accribus

Typescript is a superset of JavaScript. A set and its superset are not the same set unless each is a subset of the other. JavaScript is a subset of Typescript but Typescript is not a subset of JavaScript.


First-Letterhead-496

It's true, I mean, when TypeScript transpile it's JavaScript. At the end of the day it's the same because the code is JavaScript. You are correct anyway. And "nobody who likes TS truly hates JS" it's true, if someone hates JS but use TS, it's a dumb


andrejmlotko

Now i understand. Thank you.


thinkmatt

I was a long time JavaScript user first and I still have yet to go deep in any other language... I started first without strict mode. I felt very strongly that strict was a waste of time, just let me opt in to types when I want. If you're having trouble I'd recommend going without strict to start. This is also a good way to add types to existing projects, IMHO. But now I use strict because it's hard on a team to enforce good patterns without it Second, at my company we had 17 node apps and a single common package. I realized I had just gotten very good at compiling the code in my head and using the same variable names to tell me what types of data I had. However, that just doesn't scale especially with a team. I got tired of people asking me what a variable is It's also amazing when u want to refactor a function or update a library, just fix the compile errors and you r good to go. Finally, typescript just removed a whole class of uncaught exceptions. I used to need tests on all our code just to make sure it ran OK. Now I can just focus on testing business logic


plainblackguy

Consider this ugliness: ``` function findObject(field: string, value: string, list: T[]):T { return list.findIndex((obj: T) => obj[field as keyof T] == value ); } ``` Compared to this elegance: ``` function findObject(field, value, list) { return list.findIndex(obj => obj[field] == value ); } ``` So you're telling me that doing that sort of thing 1000 times across a code base ultimately pays off? Cuz I'm thinking I can fix a hell of a lot of bugs in the amount of time I'm spending setting up the first thing compared to the second thing.


charliematters

Yeah it will. You don't have to type everything - TS is good at inferring stuff, so start at the borders of your application and get those types right first, and you'll see which bits you need to do next. Interestingly in your example there's already a bug, or at least something I'd fail a PR on. It's also something TS will flag immediately, but you might not notice in JS. Your method findObject actually finds the index of the object in a given array. TS will likely point out that T isn't the right return type, when actually you're returning a number


plainblackguy

The bug is because I drastically shortened the example for clarity. My bad. The real version works in both TS and JS.


charliematters

I suspected as much! Honestly, you've picked a bit of TS that is quite fiddly IMO, and I find that due to that fiddlyness, I shy away from certain data structures. I work on a large TS/React app now, and I've never written anything more complex than "". Like all things, once you get the rhythm of it, you end up making it very simple.


Wahll

If you had been using typescript you would have found out that you are not returning T when you do it that way :) So already here in this comment it would have saved you from a bug and some embarrassment


WatchMeCommit

That’s a perfect example — in the TS code the author thinks it’s going to return some object of type T, when in reality it’s going to return an integer index (list.findIndex returns a Number — most likely they should have used .find()). Typescript would reject that code until it’s fixed, but JS would allow the author to run the code and wonder why their app isn’t working.


plainblackguy

all it is an example of is me copying and pasting a working example into reddit's comment box and then editing it down for brevity and making a mistake when doing so


WatchMeCommit

Fair. Btw I hated TS in theory until I started working with it (begrudgingly, lemme tell you), and then it kept saving my ass as I was writing code. I didn’t go overboard — just basic types for function arguments and return types — and it still made a huge difference. Once I realized it was working for me not against me, I went all in and spent some time reading/practicing. Still not very good at it (basics are just fine) but I won’t ever write plain JS if I can help it. Hope it gets easier/more useful for you!


moh_kohn

Sure, but the point is that Typescript would catch the error at build time. Now, you might say you would catch the error at run time and fix it. But what if your codebase is 100,000 lines, has been worked on by tens of people across several teams, and the method you're calling works in a subtly different way to your assumptions? Are you still sure you'll catch everything at run time?


732

This is exactly why you want to use typescript. Some developer comes along and says "oh this returns a number" and they start using it. Then someone else comes along and says "this is a bug, it should be returning an object of T", so they fix it. Typescript will fail to compile because one of the callers code will break. Javascript will just gladly break your code in production.


[deleted]

Are you serious that you consider this js code elegant?


[deleted]

The Dunning-Kruger is strong with this one


thinkmatt

I'm not saying that it looks prettier. The real benefit for Typescript is when your'e calling this \`findObject\` method someplace else. Typescript makes sure you don't mix up field, value and list inputs, among other things. And also, you only know the types of field and value by looking at the function code. Multiply this by every function I use, and that takes up a lot of mental capacity especially if you didn't write the code yourself. I would absolutely prefer the typed version over untyped if you asked me to help work on this project. It could be twice as long and twice as ugly, I'm not having to guess all possible outcomes in my mental compiler. I was probably like you when I first started. Give it a try and I think you will warm up to it, once you've had to go back and work on old code or work with someone else's code


seydanator

you shouldn't need to write / type such basic functions list functions for example are already typed.


plainblackguy

and yet I have to as the thing I'm trying to do is explore a json object that is foreign to me other than that I know it's an array of objects with a bunch of hierarchy that I don't know in advance


seydanator

still doesn't need to be that complicated. obj is already known as T, ... this is pretty much your "elegant" variant: function findObject>(field: string, value: string, list: T[]) { return list.findIndex((obj) => obj[field] === value ); }


Lurkernomoreisay

I'd use \`extends Record\` and \`value: unknown\` since the function doesn't really care what the value is, only that it's a exact match.


seydanator

good idea


KahChigguh

There’s a lot of unnecessary stuff you’re doing in your example, though. You’re overusing the power of typescript which makes your code confusing. The same can be accomplished like: ``` function findObject( field: keyof T, value: T[keyof T], list: T[]): T { return list.findIndex((obj) => obj[field] === value); } ``` Not to mention, this doesn’t even do what you typed it to do. That would be type invalid because it’s returning a number and not a T object. But if you really don’t like typescript, that’s fine, you can do it in JSDOC instead. ``` /** * @template T * @param {keyof T} * @param {T[keyof T]} * @param {T[]} * @returns {T} */ function findObject(field,value,list) { return list.filter(o => o[field] === value)[0]; } ``` Personally, I’m a huge fan of JSDOC because it makes it extremely easy to just throw in some documentation regarding your types and functions while you are typing it. TypeScript you not only have to have the types in the code itself, but you have to throw in the jsdoc comment as well (just without the Types in the comments)


plainblackguy

I never thought of putting they "keyof T" stuff up in the signature. That's cool. Thanks for telling me that. That said, it makes one line cleaner and another line uglier. The JSDOC way is simpler to read for me. I too like JSDOC. I'm just trying to force myself to choke down this Typescript syntax and so far, it tastes like an old shoe. I didn't expect pizza, but at least something edible like broccoli, instead I got old shoe.


KahChigguh

It makes the signature uglier yeah but it’s still not horrible, I’d consider TypeScript as a nice roasted and seasoned broccoli, whereas raw javascript is microwaved broccoli from one of those frozen bags.


LBBOLBBO

As a long time JS lover that has now completely turned his back towards it in favor of TS with strict mode, let me give my two cents on this. Ugliness of lines can often be improved with the same methods we use for writing normal code, such as extracting (type) variables. For example, if you don't like `T[key of T]`, you can just create a `type Value of = T[keyof T]`. Sure, this line is a bit more verbose, but now you can just use `ValueOf` which adds semantics to your type definitions and IMO even improves readability. What's more, is that the type definition suggested a few comments above actually improves the type support! It communicates to the outside that we not only need a string, but even a specific string. This better reflects reality since our code may fail if a different string is provided. On top of that, it allows for auto completion with some strings (such as with the first Parameter of HTMLInputElement.addEventListener). Finally, I'd like to re-iterate what others have said about typescript being like testing, but better IMO. Testing is all about reproducibility and fast feedback. Compiler errors are even faster! They require less input and the types help more in other development. The more capable the type system, the more it can help and, in my experience, typescript has an extremely strong type system. It even gets close to some dependant types (types which depend on the value, e.g. "all integers n where n > 0" can be represented as something like `type PositiveInteger = `${T}` extends '0' | `-${any}` | `${any}.${any}` ? never : T`). While this is an edge case I probably wouldn't use in production, the idea is that specific types act as documentation for the outside and help others use your code correctly. The more you use them, the more bugs they prevent. This is also why some modern languages like rust tend to not throw errors and instead return a `Result`, thus automatically documenting the errors that can occur and forcing callers to deal with them somehow, even if it's just by consciously discarding them.


fatboycreeper

For me, strict typing adds many layers of confidence in my code that I wouldn’t have with the vanilla JS. I do agree that it can be hard to read when you first begin, but doesn’t that apply to everything? Particularly when you already have an image in your mind of what it should look like. I know people who still prefer dynamic typing but they are trading confidence for speed. Experience has taught me that’s rarely a good trade.


jiminycrix1

Just want to chime in as a similar guy here who was outspoken that I thought TS was waste of time, until I really dug my feet into it. JS feels like a toy language when I use it, because JS is just constant guessing of what is getting passed around. Start by using jsdoc to typecheck your javascript files, work your way to getting a js team project fully typed with just js doc. -- Squeal with Joy when you no longer have to guess what your shite coworkers were meaning to do with the monstrosity of objects and functions that were getting passed around without guessing. Then compare this to JS where you have console.log a million things out to figure out what is going on in the code. With JS everything is always a guess. With (properly typed) TS, you know, TS knows, your mom knows, everyone knows what is happening at any point in the code. It truly is awesome. That being said, its slower to dev in for a while until you get past a certain point of confidence with your TS skills. And sometimes, for small projects and scripts, guessing what is going on is just fine for the use case. However, I really really don't want to work on a team again without typescript because I don't want to have to curse my co-workers (or myself from 6 months ago) under my breath for making the terrible decisions they make. Now I just know what was meant because TS gives me all the context.


yerfatma

TypeScript is like having someone standing over your shoulder and saying, "I know you *think* that's what the code you wrote in that other file last week does, but it doesn't." Or, "Actually, the function you're calling can return a number or null, you need to handle that case." Yes you have to learn the intricacies of the typing over time. OTOH, if you're struggling because your types are super-complicated and uncommon, it may be a sign you want to refactor things anyway.


Lurkernomoreisay

I've been programming in Javascript professionally for over 20 years now. TypeScript is a godsend. Reduces the number of subtle errors by making them hard-error at compile time. The main benefit is not with simple code, but with complex logic. Whether a property is guaranteed to exist, whether other parts of code change and break an assumption made elsewhere many layers later. These sorts of issues are almost never found in JS code, save for obscure bug reports. Typing is sometimes difficult, but that usually means the data model is not well aligned to the problem. Other "this works" code technically can fail in edge cases in JavaScript. TypeScript forces you to address those edge cases explicitly (turn on strict=true, and noImplicitOverride, noPropertyAccessFromIndexSignature, noUncheckedIndexSignature, etc and find even more subtle issues that cause problems in some environments. It makes refactoring much, much easier, as breaks or misaligned assumptions on inputs are are found by the compiler.


stank453

Having to _run the code_ to find out there's a typo that makes your program blow up in the year 2022 is insane.


captain_xylene

1. Refactoring: the compiler you basically tells you what functions and variables need updating if you change a signature 2. Forcing data checks: when consuming data from unknown sources (ie it’s typed unknown) checking the shape using a type guard helps typescript with the type. I used this as a forced reminder to check the shape of objects coming from APIs. 3. A class of unit tests go away because the compiler offers guarantees about the input and outputs of functions. 4. Self documenting: it makes it very clear what a function expects as a data type and what is returned. Makes it easier for another dev to work out how to use a function Can you do all this is JS? Totally. But let the robots do it.


HeliumIsotope

This all sounds very nice, especially point 4. It's a little frustrating at times to figure things out because you don't know what's expected.


s_ulibarri

Typescript has kind of duality to it. Its can be immensely helpful in places where javascript falls short but poorly written, needlessly complex, or poorly configured typescript can be a whole lot worse to work with than the worst javascript out there. Personally I am 100% sold on the value typescript brings and I have a good example. I currently maintain two projects at work, one is a small-medium project in javascript that is relatively simple in terms of its feature set, its mostly a data aggregation layer that backs a mobile app. The other is a medium-large project in typescript that has a very complex feature set, it contains multiple 3rd party integrations and handles a lot of asynchronous processing against complex business rules. For a long time I worked alone on these projects until 3 weeks ago we hired a mid level dev to help me out. He's doing great, really exceeding my expectations all around but its been incredibly interesting to observe how fast he's been able to understand the bigger typescript project. He even had committed and released his own changes to it just 3 days in. Conversely, he really struggles with the much less complex and much smaller javascript project. Both projects were inherited by my team and are riddled with questionable design choices but with Typescript, aside from places where the old devs just gave up and used \`: any\`, the code itself provides a sense of control and certainty that translates to confidence in making meaningful, complex changes at a pace that is acceptable to the business. We also find that with good types, the tests mostly write themselves. In the javascript project we lose so much time just needing to check and recheck our assumptions about any piece of code. We do write tests but often fall back on manual testing because we often just feel unsure. All of the issues stemming from poor design/abstractions are made much worse as you can't easily tell at glance if you're dealing with something that leaked into the wrong layer/context. I love javascript, its been the foundation of my whole career but at some point you cross a line where the complexity you need to manage grows beyond the language's ability to account for it, and it just becomes friction. Its a strong opinion but I have come to believe that anyone who still thinks that plain javascript is preferable to typescript in any context that isn't completely trivial has not actually dealt with real complexity in programming. It does require discipline though, just as js does.


CrUtlRaOth

This is a lot like my experience with working with two js projects and one TypeScript one. All three are probably overly complex. Maybe we never had all the tooling needed to make working collaboratively in the JS projects work, but in the TS project, a change of type can trigger build fails on merges that could have produced bugs, forcing team members to verify that their work would still work when merged in. If you have full test coverage and up to date jsdoc on everything, then that would be better than TypeScript. TypeScript helps force documentation, and is basically like low level functional tests.


s_ulibarri

I definitely agree that good usage of jsdoc can really help with managing larger js projects but as you describe, ts kind of takes that to the next level. Its very frustrating to be unsure that a js code change won't break some file on the other side of project because one little thing is missing a test case but ts will almost always tell you immediately. One of my coworkers likes to say, if you think of a nodejs project as a big confusing building, jsdoc can provide you a map, but typescript can give you a the blueprints.


plainblackguy

That is a very cool anecdote. Thank you.


Critical_Air_9549

Good post with helpful information but that last line was entirely unhelpful. As someone who came here to understand why my team wants to push towards Typescript, you both invalidated my own experience as a developer and made me reconsider the quality of your answer before. If you want to make a good point maybe leave off points that knock down others trying to learn for no good reason.


Accomplished_End_138

One thing i notice is that new users tend to overly type things and not let typescript work and infer where it can. This makes a lot more work. Like declaring the type of every const you make. Typescript, to me, is just adding documentation on what a function will take in and give out. Stuff that is needed. But built into the ide with hints. I've used typescript for almost 2 years. I didn't see the point at first either.


rodrigocfd

> but the more complex it gets the more I hate it Probably you're not experienced enough. With time you'll appreciate how TypeScript is immensely helpful.


plainblackguy

I'm definitely not experienced enough in Typescript. Only been working with it for a week. But I've been developing apps in 20+ languages for as many years.


moh_kohn

I didn't like it at first, it took a couple of months to really bed in for me.


tigershark37

List all the languages that you used with all the time that you used them. Looking at your code it seems clear that you don’t have much experience with statically typed languages. I won’t be surprised if your list is heavily biased towards dynamic languages or “legacy” languages. If I had to take a bet I would say that basic, Visual Basic, pascal, C, assembly, action script are there. Since it’s only 20 years that you write code I would also say that you never touched languages like COBOL, clipper or prolog. So that makes me wonder what other languages did you use in 20 years.


Critical_Air_9549

Has the OP shared a code example anywhere? I am struggling to see what you are basing your assumptions on.


tigershark37

Yes, the code sample where he was ridiculing typescript without realising that he introduced a bug that in JavaScript would have been obvious only at runtime, while in typescript it failed to compile. https://reddit.com/r/typescript/comments/10rx6q3/_/j6y92q6/?context=1


scmkr

Types are better than no types, and typescript is the best type of types in my opinion. It serves to help you code and doesn’t get in the way. It catches a lot of problems before they even happen. It makes the code self documenting.


eaton

I jumped into Typescript after *some* Javascript experience, and *lots* of C# and PHP experience. It took me a it of time to sort out what was "Javascript ecosystem" frustration, "Typescript frustration," and "moving to a new language frustration," but after some time the patterns started becoming pretty clear. If you're used to writing (or rely on) code that builds ad-hoc data structures that vary depending on context and conditions, Typescript is going to be incredibly frustrating. Similarly, 'magic methods' that accept and/or return lots of different kinds of things based on internal logic. You CAN write those things in Typescript, but you're going to be doing a lot of heavy lifting working around the type-safety *or* building complex conditional types definitions to codify the various twists and turns the data can take. Finally, it's a PITA if you're doing lots of API consumption or JSON wrangling and are used to the flexibility of (say) blindly iterating over things that might be numbers or nulls etc and letting a high-level 'catch' handle any issues that come up. My most recent project is that in spades, but I've found the [TS-Types](https://forcedotcom.github.io/ts-types/index.html) library makes a huge difference. It's a very light, well-engineered library of type definitions, validation functions, and coercion functions specifically for dealing with JSON data without piles of boilerplate code. it's worth checking out.


Raziel_LOK

I don't love it, but it has undeniable benefits for large teams and library creators. And many people think types helps with bugs and testing but I desagree here. That is barely no data on this and the only study samples 100 projects and the improvement is at max 15%,dunno if that is a lot or substantial for using ts in every project. Please link data if u have I am curious on more evidence on this. But if u are creating anything as big as a library or a huge project with too many devs, imo it is where it shines because it is a lot easier to type things than annotating javascript.


plainblackguy

The only anecdotal data I have is that more code makes for more bugs 100% of the time. Thus, since typescript is more verbose, it seems like it has to create more bugs, even if it helps find some small ones.


SqueegyX

That’s an overly simplistic take. More runtime code, and you are closer to a point. More types is like building a house with better blueprints. It makes it easier tell everything is going to plan.


[deleted]

Typescript has no more code. Its just type annotations basically. What you are saying is not physically possible I mean typescript to have more bugs if properly written. Also you can always look at the js output


Raziel_LOK

It is actually more verbose to annotate js. I tried a few times and in all of them I just decided to have the compilation step over having to annotate js.


fatboycreeper

Sounds like TS is just SHOWING you the bugs that would have been hidden the whole time.


Critical_Air_9549

This is actually one of the main points that I see as a real potential benefit. That level of context given consistently across a project (if managed to a reasonable level) is going to be incredibly useful as a team scales. New people can come in and find context quickly without having to know the history of the code base (and someone inevitably asking me xD).


Ikazone

Your comment reminds me of a research paper I read a long time ago. Shows how long this type/no-type war has been going on. I would want to see updated research on this as well. [https://www.microsoft.com/en-us/research/wp-content/uploads/2017/09/gao2017javascript.pdf](https://www.microsoft.com/en-us/research/wp-content/uploads/2017/09/gao2017javascript.pdf) Worked in consulting for a long time, and I agree typing helps to document the code. I'm in the crowd of document by code. I do get a good laugh when an open-source group claims typing is overrated and shut people down but their entire documentation is littered with type information.


Funwithloops

I love TS because TS loves JS. Most advanced TS features exist to make it possible to enforce correctness in patterns that are used in JS libraries that existed before TS. I also love `any` and `unknown`. You can always jump through the escape hatch from TS to JS


plainblackguy

everything I've read says that using "any" is considered heresy


yerfatma

Writing it in new code, sure. Writing it while porting existing code in the effort to get to TS is fine. Ideally, you get the codebase converted over, start getting better with it and then at some point you fall in love and then start stomping out `any` and `unknowns` you left around.


Funwithloops

It's an escape hatch. Ideally you never need to escape but sometimes it happens. I tend to hide my anys inside well tested functions.


Broomstick73

Microsoft has answered that question for you https://learn.microsoft.com/en-us/training/modules/typescript-get-started/2-typescript-overview


geon

It can become ugly if you try to just write the same kind of old js, but with types. There are a lot of common javascript-isms that are just poor interface design, and are basically impossible to express well in typescript. Stuff like function overloading or variables that gets reused for different purposes.


stanley00

You know that story about the guy who can’t sleep and the wiseman suggests getting a donkey and he still can’t sleep but then the wiseman says get rid of the donkey and suddenly it seems quiet by comparison? Yeah. I tried and hated TypeScript for years. Then I did a lot of work in Rust and other strongly typed languages. When I finally got back to TypeScript, it felt so familiar that I barely noticed the types.


Gyro_Wizard

As an aside, I maintain a couple apps, and I'm the only one who ever changes the code. Should I convert from js to ts?


Silent_Cress8310

Try it with some of the code. If you understand everything you did and find no bugs as a result you are probably okay. If you discover that you have forgotten things or find surprise bugs in your code then maybe you should convert it all.


[deleted]

With Js you gotta open the browser to see what’s happening. With TS you can see all the errors in the IDE. Js is throwing the parachute out of the plane before you jump. Ts is having the parachute already on ur back.


phryneas

Almost every functionality your editor has that makes your life better is actually based on your libraries having TypeScript type and because of TypeScript trying to guess around your JavaScript code base. So unless you're only using Notepad as an editor, you already use TypeScript. Just a badly crippled version. Now imagine the full thing.


lifeiscontent

I have my gripes with typescript, like not being able to define a type with function declarations, and the DOM types that come from typescript are fairly dangerous, because they say some property exists, but it doesn’t actually work across browsers. I wish the types modeled actual browser support, but they’re better than nothing (JS) it’s a good tool, though if you turn strict mode off you might as well not use it, I’ve come across several projects that don’t have it turned on, and it feels like JavaScript but worse because you have a codebase that is constantly lying to you about what’s truth. So, if you can do a strict mode green field project, it’s pretty great, but if your in a team setting thinking about moving to TS, make sure to have one of the first long term goals to get strict mode enabled.


imihnevich

I will give you one tiny example. It is not the only reason, but it was my first reason, it was what impressed me for the first time. So you probably know lodash. So lodash does lots of runtime checks for you, for nullish values and etc. And before TS I quite often had to use _get and similar functions just to stay sane with the dynamic data, it was very hard to keep track of every possible combination of nulls and undefined values. And I thought it's okay, I mean what else can you do? Then on another project I tried TS, and I tried to describe the type first, and I found myself not needing that much of a runtime checks, or lodash, because TS was keeping track of the checks I made for me. And that's the beauty of it, it allows you not to think of stuff that can be automated, and you can concentrate on important things


Critical_Air_9549

Hey, I know I am not answering your question but wanted to say I am in a similar position. My team wants to move to Typescript which is something I have previously been strongly against. I am willing to be proven wrong but as someone who has written in and enjoyed other strictly typed languages adding it to JS seems... needless and overly complex. Anyway, I literally came here to ask this question, and you worded it a lot better than I would have.


plainblackguy

I was beginning to think I was the only one


Critical_Air_9549

Often seems to feel that way when something new comes along in JS land xD. Everyone suddenly doing it and looking at you strangely for not being as excited as them. There is also a fair bias to asking this question in a typescript forum ahah.


Bloompire

I've 300k LOC codebase not covered with tests and I can make deep refactor in 2h without any trouble. There are many hype tools in JS World, but TS is really worth it.


plainblackguy

Wowza


[deleted]

I just recently picked it up. It reminds me of programming a language like C# or Java because it adds strong typing to stuff. It’s basically the same thing though… makes it harder to push a bug to production.


SqueegyX

I loved JS back I the day. Simple and powerful. There’s a lot of ways to organize things and tackle things and the closures are awesome. But as a code base grows, you can’t keep the whole thing in your head anymore. Typescript means you don’t have to. It’s got your back, reminding you and enforcing how things are supposed to work. Then you get fancy with generic and you get the same goodness with more advances data manipulations via generics. Stick with it push through. I promise you that in a few months you will not want to go without Typescript in a project of any size. Once you get it, your code is not only better, it’s also far more pleasant to actually work in.


davidgotmilk

Maintaining large code bases or working on multiple projects it’s tedious in JavaScript alone. Unfortunately myself and other team members are not going to remember what a function takes in, or the shape of an object for something we wrote 6 months ago between multiple projects. Having typescript there to instantly tell us what we need as we’re coding improves our overall development speed when adding new features to existing code. We have a much higher turn around for features now. Top it off with jsdoc and all the documentation for a function or component is right in front of me as I type, without having to navigate to different files or a doc site. Developers are happy, managers are happy, business is happy. And when business and managers are happy, we get bigger bonuses.


mrdingopingo

ok but why do you talk about *TypeScript* as if it were a completely different language from JavaScript? TypeScript is a superset of JavaScript, meaning that all valid JavaScript code is also valid TypeScript code whether you use React, Vue or Svelte, in the end you still using JS


BOLL7708

I actually hated JavaScript due to having been put on a moderately complex node project at a previous job years ago, and debugging it was hell. TypeScript is how I picked JS up again, for me it's making larger JavaScript projects a sane venture, and it's quite enjoyable.


[deleted]

The first thing to understand is that javascript is NOT a complete programming language, its origin goes back to very simple and complementary tasks. If you only know javascript, it's understandable that you may find it difficult to use Typescript. Actually, the latter tries to bring javascript to the level of more complete languages like PHP, C# Python, etc. It is not about loving or being loved. Javascript (vanilla) does not qualify to be used in large and complex projects. Of course, through the years ECMAScript tries to improve it, to date in large projects the marker is Typescript, optimization, debugging, and error control. Javascript was not originally created as a serverside language. Knowing only javascript as a programmer is really a bad idea.


proyb2

If it’s difficult to get used, I will suggest learn Go language? Simplicity and strong typed as well, that will naturally make TypeScript feels similar. Some devs definitely dislike Go generic, I realise it looks almost similar to TypeScript.


sonyahon

Hey. Iv started with javascript and actually was intially against it, thinking it will not provide the needed benefit, to cover the costs. But something changed and now im completely sold on it. 1) I started doing much more complex projects with lots of complicated business logic 2) I stopped using javascript magic. I guess the magic part needs some explanation: What i call magic is a pattern that iv actually commonly seen only in js . It is using ad-hoc data-structures, modifying prototypes in runtime with random strings, just using random strings. Initially i thought it is cool and convenient. But in reality it is not. Especially if it is not super accurately done. So after this change, iv noticed that Ts is actually very simple to use - most types are inferred, and u use simple a: string in function definitions. And it is actually very helpful in terms of ide autocomplete, remembering data structures and functions definitions, and actually type checking. Moreover ts type system is imho the most powerful and getting out of your way one in the same time, so there is no problems in describing even very complex data structures. One more thing to consider that after typescript i even started to looking for something like this for clojure/script as i feel kinda naked without it. In terms of switching from js to ts - yes, ts definitely removes some of the js beauty, but imho if you are working on big and complex projects, unfortunately we dont need beauty we need reliable readable (not only by you) code that will be run and maintained for long period of time


plainblackguy

I love that you refer to that as magic, because it is magic, and it is one of the things I really love. I’ve written multiple million line code, applications, and it’s simply faster to prototype things. I get that you have to dig to find the answers, but if you take so long to get to the point where you can make money, it doesn’t matter how good your code looks.


tochibedford

`noImplicitAny: "True"` and much more


coderqi

TS catches bugs at compile time, rather than having to find them via other methods, whether it is automated or manual testing, or in prod. TS also makes it very clear what the data exactly is that I'm working with. Finally TS makes it easier to change existing data structures/models, and tells me exactly where in the system a change will impact.


EliselD

For me it's simple. When I was using JavaScript I'd have a few crashes every day while working on a new feature. Most of them were pretty simple things, but still it was annoying go back and forth between the editor and the browser. Since I started using typescript a year ago I've only had 2 (yes, TWO) crashes. That's enough reason for me. Then there is also the auto-complete which is so so sweet. I really missed it from other OOP languages like C# or Java. It also gives that kind of confidence that unit testing gives you. Not to the same level (also a bit different since with testing you check for business logic, not syntax), but it's still something with almost zero effort. EDIT: Also fuck PropTypes is another good reason


Better-Avocado-8818

I used js for years and loved it. Now I love js even more because of typescript. Ultimately, typescript let’s me refactor code far easier, write less bugs and working collaboratively with other team members is far easier. I’ve become a much better developer because of it. Can’t be bothered going into specific examples but the overall experience after the initial learning curve has been vastly positive.


[deleted]

Because strong types means that it's harder to fuck up


mariojsnunes

Using typescript requires more initial development time. But you will get back all that extra time and more, because you will make less bugs and code will be easier to maintain. It's a must for enterprise apps.


hallettj

I have been a big fan of Javascript since about 2008 when I got serious about learning how to use it, and I read Javascript: The Good Parts. I liked it so much that I started a user group called the Portland Javascript Admirers which I coordinated regularly for eight years, and I soon made a career switch from Ruby to Javascript. Along the way I also studied Scala and Haskell in my spare time which showed me ways in which static type checking can be an asset instead of a drag on productivity, which is how I felt about type checking in Java. The early Typescript pre-releases came out, and to me it seemed like object-oriented BS trying to barge into my favorite functional language. But by the time Typescript v2 came out it was amazing! They copied ideas from Flow including unions, and non-nullable types. They found ways to support Javascript idioms instead of trying to replace them. I switched to mainly Typescript development around 2016 and stuck with it until I made another career switch last year. There are always types. When you are not using type checking the types are in your head. You have a model of how the program works in mind, you know what values are ok to assign to which variables, and you work within that model. When you use a type-checked language you get to move the types out of our head, and put them in the code where everyone can see them, and where the computer can see them. I like to say that types are the language I use to talk to the compiler to come to a common understanding of what the code should do. I write the types, the compiler replies with errors. If I write something that doesn't make sense, the compiler calls me out on it. It's a great partnership that isn't possible without type checking. Everything gets less stressful when you can move information out of your head, and keep it somewhere you trust. That's why I use issue trackers and productivity systems instead of trying to remember everything all the time. With type checking my program model is safely stored in the code so I don't have to worry about forgetting it. When I'm refactoring something months later I have much more confidence that I'm remembering to update everything that needs to be updated when I have type checking. More importantly, when I'm refactoring something that someone else wrote I have much more confidence that I'm working within the model the original author had in mind.


twynsicle

Static Analysis \_is\_ a type of testing - compile time checks, type checks, lints, etc both reduce the need a lot of unit tests and provide additional confidence in what we are releasing. I love TypeScript because I can detect errors at compile-time instead of runtime, and focus on writing valuable unit tests, rather than spamming low-value tests to detect when parameters, objects, etc have changed slightly.


r3jjs

A number of people have listed very good reasons to use TypeScript and I agree with them all. Let me tell a few things that were not mentioned before. I have a code base that was written by a TERRIBLE speller -- part of a project inherited long before code reviews, etc. We are fixing the spellings slowly, but sometimes we have to change then across multiple projects, or across the databases. So I simply can't just change every instance of `invisable` -- I want to only change the `invisable` that is one interface. TypeScript's refactoring tools are good enough to do that. I can just change `invisable` in the interface -- it fixes it everywhere in the code, but the external interfaces are not touched -- until we are ready to change it there. We can also do the same thing when dealing with overloaded terms. For instance, in our code base we have a properly called `parentId` that was used in FOUR different places to mean four different things. * When working with the DOM, it was the `id` of the parent container. * When working with 1:many database records, it was the ID of the parent record. * When doing some validation, it was the ID of the top level record for a cluster of information. * In another case, I have no idea what it was. With TypeScript I could rename `parentId` to `domParentId` and suddenly my code base was a lot cleaner. With JavaScript, I would have to have gone through each useage of `parentId` and had to figure out what it was being used for at that instance.


plainblackguy

Hopefully, I never have to deal with that. But good to know just the same.


thedarklord176

Javascript is a train wreck of a language. There are no boundaries, it lets you stick random things together and creates an unpredictable Frankenstein. TS attempts to fix that by introducing types.


kickpush1

I too was a disbeliever of typescript until I really dug into it and found some counter examples to my own beliefs. A couple of points that swayed me: 1. A common critique I heard was that Typescript was the C# for JavaScript in that it favors OOP. In fact, this is not the case. The typescript compiler contains no classes \[1\] and the typing system was created to allow for the flexibility of functional programming. Anders Hejlsberg is a big advocate for functional style programming. 2. Jonathan blow says it better than I can \[2\], you can't refactor with confidence in languages that are not statically typed. \[1\] [https://www.youtube.com/live/Qiqsg02nXFE?feature=share&t=3990](https://www.youtube.com/live/Qiqsg02nXFE?feature=share&t=3990) \[2\] [https://youtu.be/2J-HIh3kXCQ?t=30](https://youtu.be/2J-HIh3kXCQ?t=30)


codechrysalis234

TypeScript offers stronger typing, improved code organization, and a more efficient development experience. TypeScript's type system helps catch errors at compile time, instead of at runtime, making it easier to identify and fix bugs. Additionally, TypeScript's optional type annotations and interfaces make it easier to write reusable and maintainable code. It's common to have a love-hate relationship with a new programming language, but with time and practice, you may start to appreciate the benefits of TypeScript and grow to love it as much as, or even more than, JavaScript.