5

Pitch me on TypeScript

 2 years ago
source link: https://dev.to/ben/pitch-me-on-typescript-1n5n
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Pitch me on TypeScript

Pitch me on... (8 Part Series)

Part of a new series! Feel welcome to dip in and weigh in on a past question.

Let's say I've never used TypeScript before. Can anyone give the run down of what the language does and why you prefer it? Feel free to touch on drawbacks as well.

Discussion (51)

pic

CollapseExpand

I can’t believe this doesn’t have more discussion yet! My favorite part about using Typescript is that it’s self documenting! When you specify the props and the return type when defining the function and you’re using an editor like visual studio code - wherever you call the function you can hover over the name with your mouse and it tells you exactly everything about that function.

An added benefit for us React devs is that it helps you with remembering to send all required props to a component in React since you’re able to pre-define prop types.

It’s balanced. Depending on the project you’re making, you can configure Typescript to catch more or less code quality inconsistencies in the config file!

Comment button Reply

CollapseExpand

I've never actually written any serious TypeScript though I've been working with JavaScript for a while. Even for me, though, the self-documenting nature of TypeScript is really helpful. For example, when I'm looking at an npm package to see how to use it TypeScript makes it easy to understand. I read it all the time.

Comment button Reply

CollapseExpand

Yeah exactly! Even when you aren’t using TypeScript it’s beneficial that people have written npm packages with TypeScript. Thanks for your contribution to the discussion. That’s another great point.

Comment button Reply

CollapseExpand

The self-documentation is definitely one of my favorite parts. Used correctly it helps me come back to my code months later and understand what the heck I was trying to do.

Comment button Reply

CollapseExpand

Can you suggest some good resource to learn typescript

Comment button Reply

CollapseExpand

I've written about it before, but the big things for me are the refactoring story, discoverability, avoiding silly mistakes, and adopting into as much type safety as you want. For example, you can add TypeScript (TS) to your project and enable the compiler options to allow for JavaScript (JS) files. Just that alone you'll already see a benefit. I would suggest being as strict as possible, but when migrating a project from JS, this is a great way to do this.

Generics and having types inferred from other types is what also makes it super powerful. Is it a silver bullet, no, but it's a great tool.

And even if you don't use TypeScript, you still get a lot of its benefits if you're using an editor like VS Code. It's what provides Intellisense and refactoring to your JS projects (as well as TS projects)

#vscode

Official tag for Visual Studio Code, Microsoft's open-source editor

Comment button Reply

CollapseExpand

TypeScript makes you a better JavaScript developer

I've been using TypeScript since its first public release almost 10 years ago (version 0.8 was released in October of 2012), and if I had to tell you a single reason to use it, then I would say:

"It makes you a better JavaScript developer".

Some benefits of TypeScript

Folks generally try to pitch TS as an amazing tool for static type checking, but for me, the best thing about it is that if you learn how to write proper TS, then you become a better JS dev because you lose that misconception that JS "doesn't have types" (because it does) and you become more conscious about JavaScript types (avoiding falsy/truthy evaluations, doing the correct parsing for values, and so on). If you use the same "good practices" that you'll use with TS in a JS project, you write better JS.

You get benefits from TS without using it directly, when you install dependencies and suddenly you get a great DX with autocompletion and error checking, is because the library is either written in TS or has types defined, and your editor picks on that and uses it to make your life easier. You can even "use TS without TS" by writing JavaScript with good JSDocs:

/** @param {number} addend1 */
const add =
    addend1 =>
    /** @param {number} addend2 */
    addend2 =>
        addend1 + addend2;

add("nope"); // You get an error here in your editor telling you to pass a number

And this is not even getting into how great refactoring is, but there are other comments here talking about that, read those a well!

Common arguments against TypeScript

Generally, the arguments against TS are kinda flaky, one I discussed in an article of mine is that TS doesn't do type validations for you, but that's a good thing.

Another common argument is that TS is "more complex" than JS, but I would argue that folks saying that didn't have to deal with a complex JS app. When you write TS you're writing more complex code first, dealing with the complexity earlier, which makes the total complexity way lower.

Some folks also don't like that TS "yell at them" while they are coding, but from my point of view, I prefer TS yelling at me in dev than JS and clients yelling at me in prod.

Finally, an argument I've seen quite a lot and is kinda ridiculous, is that they compare TS to CoffeeScript, and those two languages are very different. CoffeeScript is an entirely different language to JS, that compiles to a JS code that doesn't look like the code you wrote:

# You write this:
add = addend1 -> addend2 -> addend1 + addend2

# You get this:
var add;

add = addend1(function() {
  return addend2(function() {
    return addend1 + addend2;
  });
});

TypeScript on the other hand is a "superset" of JS, which means that you write JavaScript with some extra stuff on top (the types), and the resulting JS code generally looks like what you wrote:

// You write this:
const add = (addend1: number) => (addend2: number) => addend1 + addend2;

// It compiles to this:
const add = addend1 => addend2 => addend1 + addend2;

Don't take my word: Try it!

My tip if you don't know if you want to code with TS is to just try it by creating something with it. If at the end of the day the benefits aren't compelling enough for you, then you can just keep using JS.

Cheers!

Comment button Reply

CollapseExpand

Don't bother using typescript, unless you want to avoid classical coercion mishaps due to JS' weak types, write code that should be maintained or used by other people including yourself after a few weeks or work professionally in front-end. You don't need the comfort of helpful IDE Integration, because obviously you're omniscient at least in terms of your project. It has a transpilation step that could take up to a few seconds and nobody got time for that, right? Even though it allows you to use more recent ES standards and finds bugs in your code. But you're not going to need that, because you know all browser versions from msie8 and their weird quirks by heart, don't you? Long story short, you don't want typescript, unless you do, don't you?

Comment button Reply

CollapseExpand

Pros: type safety will help you catch errors and save you development time, esp since you can see them at deployment before run-time

Cons: if you're a fan of strict type safety, the partial types might annoy you. also, you probably don't need this for small applications. no big performance benefits over JS since it's a superset of JS so if you're looking mainly for that you can try web dev with Golang or Rust or something similar.

Comment button Reply

CollapseExpand

I was an extreme skeptic on the use of Typescript over just regular Javascript. When my team decided to try an experimental project with it on AWS Lambdas, I saw some benefit in it when I imported the aws event interfaces. I thought, oh this could be really useful for asserting an API interface and getting all the intellisense for that in vscode so I don't have to look at docs as much.

Because of that thought, a year later my team moved an existing legacy project to GraphQL. On the FE we ran a script that used a codegen tool: graphql-code-generator.com/
This hits the introspection endpoint on graphql and genrates all the types for queries and mutation and fields. It will also generate an sdk for your FE GQL queries, which are typed of course.

This was the point of no return for me and I commited to TS 100%, at least in the work environment. It saved so much time and made it so much more enjoyable to work with the data layer in the FE.

Occasionally I still spin up some small projects at home using just a node script but when it grows to a certain level of complexity, I start missing TS and feel the urge to define some interfaces, so I'll end up switching over back to TS pretty quickly. In a team environment I wouldn't consider going any other way as it just saves so much time and grief and no one has to interpret the intention or parameters of functions, etc. We do have at least one team member that hates Typescript. Sometimes he complains about how a particular typing error is just wrong or unnecessary but when one of us looks at it, it almost always turns out that TS was trying to help him cover a case he hadn't thought of or that he had a wrong concept of what the data was. On the other hand, that developer is very good at running down production bugs so I guess there are different strengths and preferences out there and it depends on what type of programmer personality you have.

For myself, if it's a question of, do you want to move fast and fix bugs in prod vs, take a bit longer solidifying your data abstraction and have less bugs later, I'll go with that latter choice.

Comment button Reply

CollapseExpand

Everything TS is trying to do is done better with eslint-plugin-jsdoc. It lets you document the types, and as you write your code your editor will do the exact same thing it would with TS types. However on hover, it doesn't just tell you the name and type of a variable, it also gives you the context of what it is, and why it exists (the stuff that actually matters).

Cons of TS:

  • SLOW: TS is notoriously slow. On any project of decent size expect to save one file, wait 20s seconds for the entire project to compile, then the page refreshes. It removes you from the flow of coding. Inexcusable experience.

    • JSDocs - No impact on speed, other than the time it takes to lint, which can be done in the background by your editor and highlighted in your code in real-time.
  • Learning curve: Everyone knows JS, only some people know TS.

    • JSDocs - No learning curve just do eslint --fix and it starts writing the comment block for you. You fill in the details, run eslint --fix again and it corrects your formatting and tells you what you missed. Level of enforcement is up to you.
  • per-character annoyance: If you type a single thing wrong, your compiler is mad.

    • JSDocs - per PR annoyance: if you want to wait until the end of your PR to do all the linting before it gets merged, that's fine, it's just linting.

Pros of both:

  • autocomplete (identical)
  • warning of potential errors and mismatches between expected types (identical)
  • code quality enforcement (eslint does a better job)
  • documentation (jsdocs does a better job)
  • being trendy bullshit (actually jsdocs doesn't do this one, hey TS is finally better at something!)

Problems of both:

Editors are using the TS engine to give you hints/warnings, and honestly, it's pretty dumb. Over-reliance on it causes more errors than just not using anything like this at all. I have seen people write up interfaces for 3rd party API's and be done. No safety checks. Like..... they genuinely don't know why that's really bad. There are also "runtime bombs" where your code will break in production and the compile time checks aren't smart enough to figure that out.

Neither of them are good for runtime checking. See: dev.to/thejaredwilcurt/comment/1212g

Comment button Reply

CollapseExpand

Considering JSDocs is lagging behind in keeping updated to the newer js specs, Typescript is only real way to go if you want a stable, large scale application in Javascript ecosystem.

Ironically, I just use the typescript only for its datatypes, keeping the actual code as close to javascript as possible. Only other thing I use from typescript is private properties, but I am slowly migrating that skill into JS private properties syntax with#var in newer code that I write.

Comment button Reply

CollapseExpand

ReScript - high quality js compiler without the OO garbage or unsound typing

Comment button Reply

CollapseExpand

And without the npm ecosystem 🤣

Comment button Reply

CollapseExpand

sadly, you end up using js/typescript libraries for a portion of your work and rescript-react ends up depending on react, which is why I am more excited about elm, but if someone is considering typescript for frontend, then one should at least try rescript before settling on typescript.

Thread

Thread

I tried rescript like 6 months ago. I quit when I saw how hard is to import the basic of "fs" or "path" from nodejs.

Thread

Thread

Makes sense. But for front end, it's not as big a deal. There are repos that show common node library bindings, but I would only use rescript for front end currently.

Comment button Reply

CollapseExpand

I feel like ppl are doing the pros/cons or a deep dive below👇 whichbis all well and good.... But I'm gonna pitch it!

You should use typescript because it adds a robust type system you can incrementally adopt with ever growing support from the community and your favorite libraries not to mention the weight of Microsoft behind it. A fully typed codebase will allow you to do powerful type driven refactoring 💪. And beyond the editor and DX you can enforce type safety in youe CI pipelines. Typescript lets you progressively type your codebase with escape hatches like unknown and any. The documentation is incredibly well maintained and easy to navigate to learn, and aince it's open source you can easily find the context of more complex features and even learn a little type theory along the way if I have time and interest.

Comment button Reply

CollapseExpand

One thing I think needs to be called out more:

Just because you're "writing TypeScript" doesn't mean your code is actually being "type linted". You have to understand what your build process is doing.

For example, Vite:

"Vite only performs transpilation on .ts files and does NOT perform type checking.
...
Vite uses esbuild to transpile TypeScript into JavaScript which is about 20~30x faster than vanilla tsc ..."

Increasingly to keep things snappy a lot of default workflows are transpilation-only, so unless there is a deliberate "type check step" somewhere, type errors and warnings may only be caught casually in the editor/IDE, if at all.

Comment button Reply

CollapseExpand

Pros:

  1. Statically type => type safety
  2. Statically type => type safety
  3. Statically type => type safety

Cons:

  1. Library compatibility issue
  2. Transpiling issue
  3. Web development is really dynamic in nature due to API calls, so type error is occasionally raised but the code should work in reality

In my opinion, all is about the typing system, without that, most of the benefits (Intellisense, debugger, etc) won't exist. Also because of the types, weird/troublesome errors just pop up every now and then. That said, I always try to achieve as much type safety as possible since it's valueable in the long run.

Comment button Reply

CollapseExpand

Imagine you are a new recruit on a big project written in Javascript. The task is simple:

  • Can you please change address of users so it is no longer just a string but it is an object containing zipCode, street, etc.?

You then start a Find in files search for the word: address.

Oh no. 😐 More than 200 results have come up. Some are comments, some are related to users, most are not. Some did not even come up as some folks made a typo: adress. You don't know until you have read the code for every occurrence of every address string. Good luck!

What if someone could have given you a crutch during development time: some extra annotation to know which address-es are related to users and which are not? To encapsulate in some meaningful type. To know the interface for every function in the codebase... Something that you can erase so you can stay compatible with the demilitarized zone of the frozen fronts of Browser wars: the one allowed language: javascript.

This is TypeScript. A tool, just like your IDE that can save a tremendous time if you learn how to handle it. If you write JS... Hey you already use it! Remember that nice library which your IDE immediately suggested the right object, function, parameter? Yes, the library had provided its typings to you. That's why it's so nice.

Don't be just some any when you can be somebody. Use TypeScript today!

Comment button Reply

CollapseExpand

I like TypeScript, but...!

I'm an average dev that was never very fond of statically typed languages like Java or C.

When I learned it in school and university I resented it.

At work I learned langauges like PHP and JavaScript, and they felt much more lightweight. It felt like finally learning something that was created with a getting things done attitude.

Obviously, these dynamically typed languages came with their own downsides in the long run. So, I really appreciate TypeScript helping out here.

But I think, I mostly like TypeScript because I'm already veeery deep into JavaScript. Like, I have most of the types in my head when coding. This means, TypeScript feels like simply writing down what I have in my head and don't have to remember it all the time. Which is nice.

But I think, for people less versed in JavaScript it can feel a bit confusing, because the not-so-optimal type system of JavaScript (and in turn TypeScript).

I know the idiosyncracies so it doesn't confuse me... okay sometimes it does, and that is actually nice, because TypeScript shows me where my model was flawed. But yeah, when you get such errors while still beginning with programming it's daunting.

What I also like about TypeScript is the opt-in and structual typing. You can always throw an unknown around and clear it up later and if something is simply called different, but has the same structure, things still work out, which is a huge improvement over Java.

Comment button Reply

CollapseExpand

Hello, I am here to bash TS, specifically a particular painpoint I have found that was not mentioned yet. I submit this to provide contrary evidence to its merits, not necessarily as a verdict; TS may or may not make sense for any particular project.

As is often the case with technologies with feature bloat, users will inevitably misuse features available to them. For TS, that would be the rather ambiguous nature of interfaces vs enums vs types vs classes.

I strongly recommend all engineers to avoid object oriented paradigms whenever possible and instead favor functional programming and composition. TS tries to open that door, but at the same time attempts to support OOP paradigms based on traditional languages. As such, we wind up with these not so clearly defined concepts, complimented with the usual conventions that follow them around (ISmurf, IServlet, IResponse...)

I just find that languages that offer this many features give rises to codebases swamped in an unhealthy blend of OOP code, OOP code with anti patterns, mixed with functional and compositional approaches along side it.

Comment button Reply

CollapseExpand

You're actually complaining about JS if you think about it. TS is just a superset of JS, so that multi-paradigm thing you find so annoying is actually coming from JS. I agree that enums suck, but similarly to JS, you can just avoid classes and 💩 like that, and stick to FP stuff.

Comment button Reply

CollapseExpand

CollapseExpand

Learn a typed language and understand why it's important. Then come back to JavaScript and it will make sense.

However it's a painful thing to view, my eyes really can't take the extra bloat and cognitive load at first is always a pain. But we adapt and then learn to rely on the predictably and make less assumptions because it also self documents the inputs and outputs.

I wish the error messaging was more clear though, sometimes it can be a proper mystical journey on why a particular type is incorrect when there are many of them to soft through. (Keep it simple I guess 🤷🏾‍♂️)

Comment button Reply

CollapseExpand

TS adds a sweet mental map for you when writing code. Especially for bigger applications. I get Marco's point on self documenting code and I feen like there's even more to it. Let's make a comparison:

  • In Javascript, you might wonder: Why did I write this part of code? Why the naming? Have I seen this type of data structure before?
  • In Typescript, well you probably wonder the same. But there's an additional layer of information that describes logic and data.

So next to the function itself, TS provides this abstract construction of static types and enriches code with context. I found this extremely annoying and limiting when I started. Right now, I use TS whenever I kick off a new project. Even the small ones which I know I'll touch more than one during the coming weekends.

Comment button Reply

CollapseExpand

I would like to add that TypeScript is much better at communicating fundamental object oriented principles over JavaScript.

If you're only used to writing JS, you might not have a clear picture of how interfaces, abstract classes, access modifiers, and return types can not only simplify a design but also greatly communicate intent.

This is especially true if you are trying to learn design patterns, or understand how JS is quite different from other programming languages.

Comment button Reply

CollapseExpand

Typescript union types is a blessing in disguise. Very useful when you are expecting an input which might be of different types. Say for instance, you are expecting a number as input. You don't have control over the input type, it might be a string or an int. You can declare a union type as follows:
type stringOrNumber = string | number ;

Then you can use the variable in whichever way you want, knowing fully well that what you have is a string or an integer. Say an input of array was passed, you'd get a typed error and the code won't run. Saves you a lot of time ;)

Comment button Reply

CollapseExpand

Typescript is great but personally I see a world with ALL the benefits of it without writing a single line in the near future. I wrote my thoughts here -> devblogs.microsoft.com/typescript/...

Comment button Reply

CollapseExpand

it will make your journey shorter and life easier, it will make things clearer, you will know what every variable and every object is of what type and what you can and what you can't do with your objects and vars ... it gives a beautiful intelliscence

Comment button Reply

CollapseExpand

I can say from my experience, using Typescript from the beginning of a project has always saved me time in the end, and helped me catch little "gotchas" through the process.

I'll give one example to the many that people have already posted. I have an API that I built that uses the following stack: Postgres > Prisma > A service layer that I built > a Graphql layer > HTTP Server for incoming requests. By defining my prisma schema and using Prisma's generators, I got all my model types for free as well as all the operations I can do on those models - AND if there is something subtle, like querying for a single record that could possibly come back null, Typescript spits out a warning if I don't handle the null case, so it's coercing me into deeper runtime safety checks all the way through. Then, I used the Graphql Schema with Grapqhl-Code-Generator to spit out types for everything at the Graphql layer and public facing API. I can then use those types through the whole resolver chain to make sure I'm returning the correct data and all the resolvers are implemented that need to be implemented, before I ever have to run the app. Most of the edge cases are addressed by virtue of TS catching when things can be one of many types, possibly undefined, etc - and not letting me pass values along until these cases are handled. Through some creative use of generics and type flowing I was able to type check the whole stack, all the way up to the resolver root, complete with typescript warnings whenever I changed the graphql schema and re-ran the generator. Any errors spit out by TS would point me to exactly what I needed to address.

THEN it got even better. This was a small MVP project so I went for code first, tests later (which you don't do, right?) and I found that a lot of the cases I would have written unit tests for..... were already accounted for by the TS compiler! So not only did I save dev time, I saved test time and debug time and the mental overhead involved in all 3. Sure, I could have written the tests anyway, but lack of time and the feedback from TS made that a lower priority.

All in all, this proved the point that I suspected. The initial setup and working out the type flowing- and learning how to use Graphlq-Code-Generator while doing this one - was very easily offset by the dev speed I maintained at the back end of the project.

Some common complaints I've seen on TS:

  • Slow compilation times - I recommend not using the standard typescript compiler if this is an issue. Set the compiler option in your tsconfig.json of "noEmit": true, and just use TSC for type checking. Use something faster to transpile when you are ready. I like Vite for this. There are also ways to hook into the build steps to run a type check from TSC before the build and fail it if something doesn't jive, and your IDE can make suggestions during dev.
  • Noisy code - This is a fair point. There is a lot more going on in a TS file. I can offer this observation though: by working through the types in each file, you are forced to more deeply consider the code you are writing, and since there is more to each file, it is much more apparent when something is trying to do too much. Thus, greater modularity and separation of concerns is encouraged by default.
  • No types for data from REST api's, having to write your own, and your code breaking when the API changes - Your code would break when the API changed in vanilla JS anyway. I don't see this as an issue specific to TS. At best, some forward thinking companies assemble type libraries for their API's or use OpenAPI which you can then use to generate types, or have opted for Grapqhl which can be introspected and types can be generated. It can be done and it's not as painful as one might think.
  • Complicated setup - I'll grant that setting up typescript is more complicated than setting up a standard JS project, but not really by that much. At one point you didn't know what all the stuff in a package.json file did, but you probably learned it along the way. This is the same thing, and once you know it and poke around with configs a few times it gets much easier. Also, most frameworks (React, Svelte, Vue, etc.) have bootstrapping commands that allow you to bring in TS already set up when you start a project.
  • Sometimes difficult to understand error messaging - I actually totally agree with this one. I've learned a few tricks to unpack what TS is telling me sometimes, but when you get into nested generics and complex types the error messages can turn into dumpster fires fast. This area of the ecosystem needs work. A quick google search of "Typescript errors are hard to read" proves that the internet at large agrees.

Comment button Reply

CollapseExpand

Having a static typed language gives you the possibility to work on a project without having to run it, this is the thing I most prefer about ts compared to js.
It also lets you describe all your code so you don't need to jump around the codebase to understand what is what.

Comment button Reply

CollapseExpand

I see TS merely as a tool for JS, and not a superset or flavour of JS. Use it sparingly, and it is useful. Don't take it as a religion. TS has plenty of very obscure features, they sound like voodoo, it's not good.

TS: don't use everything it offers just because it is there. Same goes for JS.

Comment button Reply

CollapseExpand

Work in a React with pure js for about 6 months. Then do it again with a typescript based React code base.

Comment button Reply

CollapseExpand

Pros:

  • Cleaner code
  • Static type checking
  • Less compile errors and debugging

Cons:

  • Longer project setup
  • You have to write more code
  • It still compiles to vanilla JavaScript

Comment button Reply

CollapseExpand

TypeScript is fun to read. TypeScript is not fun to write.

Comment button Reply

CollapseExpand

No pitch here. I went back to not using it, and feel more productive

Comment button Reply

CollapseExpand

It was created by the most powerful Sotware Language Company in the world. The one who owns Github.

Comment button Reply

CollapseExpand

It's JavaScript, with all the fun taken out. If that's your thing

Comment button Reply

CollapseExpandCollapseExpand

I have a whole video about it 😛

Comment button Reply

CollapseExpand

Makes refactoring a hell of a lot easier.

Comment button Reply

CollapseExpand

Ive always wanted to learn typescript

Comment button Reply

CollapseExpand

This one's easy: You can build your frontend, backend and mobile apps using a single language with similar build/test tools.

It's like a global currency that you can spend anywhere.

Comment button Reply

CollapseExpandCollapseExpand

Pros:

  • Slight improvement in IDE experience (although JSDoc gives you that same benefit with vanilla JS)
  • Shows other people you’re smart and doing the current thing

Cons:

  • Overhead in all parts of the workflow
  • More layers of abstraction
  • Doesn’t guarantee much of anything when your app is consuming data it didn’t originate (that’s virtually every web app)
  • Doesn’t help with any actual web-specific challenges, like poor network or no network, styles and layout and a11y, device variables, browser variables, session management, etc.

Comment button Reply

CollapseExpand

Doesn’t guarantee much of anything when your app is consuming data it didn’t originate (that’s virtually every web app)

That's such a common argument, and it only shows that folks don't really understand the difference between types and validations 😔

Comment button Reply

CollapseExpand

Or does it show folks do really understand the difference and they’ve realized how little value there is in static type checking for a piece of software that deals primarily in data it has no control over🤔

Thread

Thread

Do they really understand it if they think they have "little value", tho? I mean, there are some folks out there that also don't see value in linters, formatters or any other tool designed to work with teams at scale, but then we are talking about personal preferences more than talking about the actual value of those tools 😕

Comment button Reply

CollapseExpand

Comment marked as low quality/non-constructive by the community. View Code of Conduct

How about no. Write your own blog article.

Comment button Reply


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK