DEV Community

Cover image for Pitch me on TypeScript
Ben Halpern
Ben Halpern

Posted on

Pitch me on TypeScript

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.

Latest comments (48)

Collapse
 
netanelhaber profile image
Netanel Haber

I wrote about this actually! (Tl;dr: Writing in TypeScript is like moving your js code from notepad to an IDE: You get refactoring, documentation, code completion and more): netanel.dev/blog/TypeScript,%20Typ...

Collapse
 
deltd3v profile image
deltd3v

How many of you have ever built very VERY large Web dev projects? 🤣

It's incredibly frustrating if you're only dealing with JavaScript.

Collapse
 
drsensor profile image
૮༼⚆︿⚆༽つ • Edited

Only one word.
"King of Web"

Although there is many alternative™, you can't call yourself web developer without knowing Typescript 😂

™: Hagel, Flow, dart2js, ReScript, Elm, PureScript, anything else?

Collapse
 
ikembakwem profile image
Ikechukwu Mbakwem

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 ;)

Collapse
 
latobibor profile image
András Tóth • Edited

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!

Collapse
 
codingjlu profile image
codingjlu

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

Collapse
 
elsyng profile image
Ellis • Edited

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.

Collapse
 
jzombie profile image
jzombie

Makes refactoring a hell of a lot easier.

Collapse
 
charlesfries profile image
Charles Fries

Pitch me on JavaScript

Collapse
 
nikfp profile image
Nik F P

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.
Collapse
 
sirseanofloxley profile image
Sean Allin Newell

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.

Collapse
 
peerreynders profile image
peerreynders

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.

Collapse
 
kayis profile image
K

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.

Collapse
 
thejaredwilcurt profile image
The Jared Wilcurt

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

Some comments may only be visible to logged-in visitors. Sign in to view all comments.