re: Practical Ways to Write Better JavaScript VIEW POST

TOP OF THREAD FULL DISCUSSION
re: Thanks, it sounds interesting. I'll give it a read

The whole "only being a compile time safety net" is something I told myself before I forced myself to give it a propper go.

The power of being able to refactor a large app without breaking something is invaluable for me.

A good example is the ability to define the type of a return from an API. If this shape changes in the future with a simple modification of your type you can now ensure that not a single part of your code base references a node which no longer exists without erroring before building.

It has solved more errors on a refactor than I can count - On any large application if you want to have any confidence modifying code it's worth the overhead :)

I'm not arguing against your use case, I'm sure TS helped there, but that can also be done using pure JS. With the proper test cases and JSON schemas put in place (I'm making the assumption you're talking about a JSON-based API), the same thing can be achieved.

Again, not arguing against your use case, I'm just trying to find one that is clearly easier to implement in TS than in vanilla JS.

My 2c:

TypeScript makes your IDE smarter, though you have to do the type definition work. Ever worked with objects with many properties (especially nested properties) and forgotten something? Or have to keep on referring back to some file where it was first defined? Or accidentally slapped on extra properties that should have been somewhere else? TypeScript won't fix the world, but it does help you to avoid these errors and I find that the intellisense improvements speed me up greatly. Functions don't just accept or return arbitrary objects: I can easily refer to structure definitions in code I haven't seen before and get good autocompletion.

Yes, you could also achieve some of this with jsdoc, but if you're writing jsdoc, you might as well define types. It will actually be quicker 🙂

TypeScript is also, imo, the easiest way to get modern syntax like async/await and import syntax. I've found it easier to set up than Babel.

All JavaScript is TypeScript, so you don't have to go "full-on" - adopt what works as you decide to. You can introduce it to an existing JavaScript codebase without having to change your existing code - it can deal with .js files and if you decide to convert some existing code, change to .ts and deal with any warnings/errors. You can also relax the compiler, but I've found most usefulness with stricter settings (like not allowing 'any') and projects where things get the murkiest have been where people avoid the typing system. My advice is to rather try to find / define the correct types than telling the compiler not to bother.

code of conduct - report abuse