What is TypeScript and why should I use it over JavaScript?
Posted by PastimeNow@reddit | learnprogramming | View on Reddit | 55 comments
Hi guys, I've been coding in JavaScript for a few years (inconsistently but I have decent experience). I've done a few projects in it. The next project I was planning to work on primarily uses TypeScript in their documentation, hence I decided I would learn more about TypeScript. As far as I understand it is a better version of JavaScript, it's more clear, you have more control over the datatypes. But I don't understand in which scenario it is better to use TypeScript, are there things TypeScript can do but JavaScript cannot? How is it an advantage to use TypeScript? Why would you need better control over the data types when JavaScript does it all automatically?
PhiLho@reddit
I would say that TS doesn't do things JS cannot do, from a functional PoV, since TS is "compiled" to JS, and often the result is very close of the initial code.
Why would you want a better control over the data types? To take a trivial example, you can make a function taking a number to do a computation. In JS, you can call it with a string (a mistake easy to do), it will throw a runtime error and the program will stop. TypeScript would make an error at compile time, and even at the time you type the call, in a smart text editor like Visual Studio Code or similar. So you can avoid some runtime errors and gain some time.
In a less trivial but similar and more realistic case, you can pass a complex object, TS will warn if you pass the wrong object (type). And you can build relatively complex types.
Likewise, in classes, you can make private members. It was simulating them actually, but it was useful. Now JS has real private members.
In short, TypeScript adds rules that limits you, which can be a good thing to avoid trivial and subtle programming errors, and it can be expressive, leading to quite self-documenting code, and it helps smart editors for auto-completion and inline documentation.
BlueSoup10@reddit
TS types can get so complicated you can make calculators with them: https://youtu.be/t4tjMeFYWEM?si=saRupPAHBR0QwV4-
RomanAbbasid@reddit
they can run doom
jlanawalt@reddit
That would be inefficient. You could use WASM, and asm.js before that.
RomanAbbasid@reddit
I get the feeling efficiency wasn't much of a consideration for that project
PastimeNow@reddit (OP)
ohh........ my god... i'm learning typescript.
-wtfisthat-@reddit
Now that is some next level commitment! Now he just needs to optimize it down to a reasonable frame rate! /s
Dr_Quink@reddit
Holy Shit. That’s just the best kind of insane.
jlanawalt@reddit
And obviously you can also do that in JS
mfc1__@reddit
Typescript is transpiled, not compiled.
PhiLho@reddit
That's why I have put "compiled" in quotes. 🙂 But others have better answered than me.
SnugglyCoderGuy@reddit
Its all just trabslating instructions from one form to another
FishfoxNuro@reddit
A transpiler is a compiler. It's just unnecessary pedantry, especially with how often things are compiling to bytecodes and intermediary languages.Â
Strikeeaglechase@reddit
You can argue the semantics between compiler, transpiler, source-to-source compiler etc, but TypeScript calls it a compiler: https://www.typescriptlang.org/docs/handbook/2/basic-types.html#tsc-the-typescript-compiler
GeneralPITA@reddit
Well said - I like the way a typed language will let me know the parameter I need to pass is 1234 and not "1234".
ConsLeader@reddit
If you’re trying to get serious with TypeScript, I’d also check out the boot dev platform's Learn TypeScript course. It’s a full‑length, project‑based intro that walks you from basic types up through generics and conditional types.
Physical-Positive732@reddit
TypeScript doesn't let you do anything JavaScript can't — it compiles down to JavaScript anyway. The value is entirely in the development experience and catching errors before runtime.
The click moment for most people: imagine you have a function that expects a user object with a
nameproperty. In JavaScript, nothing stops you passing in an object withoutname— you find out at runtime when something crashes. TypeScript catches that at the moment you write the call.For small personal projects it's optional overhead. For anything with more than one developer, or any project that'll grow over months — TypeScript pays for itself fast. The project you're looking at uses it for exactly this reason.
Practical advice: don't try to learn TypeScript in isolation. Start converting your existing JS project to TS file by file. The errors it throws will teach you more than any tutorial.
saimumislam@reddit
I don’t think TypeScript is a must. It definitely helps with IDE support and catching errors early, but you can get a lot of that safety using tools like Zod, Joi, or PropTypes for runtime validation.
Flow is also an option for static typing, though it’s not as widely used anymore. At the end of the day, JavaScript being dynamic is part of what makes it flexible and enjoyable to work with.
Suitable-Turnover597@reddit
typescript It is needed solely for typing and convenience, it does not affect the final code in any way, but makes it more reliable due to the fact that during development in typescript you will write more strict code, the IDE will highlight and prompt you a lot, and because of this there is less risk of making a mistake in the final build
kilkil@reddit
typescript is mostly the same as javascript, but with static typing. javascript itself however only supports dynamic typing.
Static typing is generally seen as better, for anything larger than a small script. This is because it allows you to catch certain very common kinds of bugs at compile time, before your code even runs. Mostly these are bugs caused by accidentally passing the wrong value to a function (e.g. a function requires a string, but you gave it a number).
Some people dislike static typing because it usually requires more work upfront, to design your type definitions. And changes or updates to the logic will often require changes/updates to the type definitions as well.
But in my view (and in many others' view as well) this is more good than bad. It just means static typing forces you to think about the shape of your data, which is essential for good program design (meaning less bugs to fix later).
Having said that, Typescript specifically has some downsides which other statically typed languages don't. In particular, Typescript suffers from the fact that it is essentially "bolted on top of" Javascript. This means that Typescript is forced to have escape hatches such as "any" and "unknown", weakening its type system. Also, more worryingly, 3rd party libraries can sometimes (though rarely) have incorrect type declarations, where their Typescript type definitions don't match their actual JS code.
All in all, to answer your question: Typescript is appropriate to use for any project that is more than just one small scripting file. It has a learning curve and you will spend time on additional work that you wouldn't do in JS (designing/refactoring your type definitions), but it is worth it because it eliminates a whole class of bugs.
Other considerations:
Typescript is a compiled language, which compiles to JS. This means you will likely need additional configuration (mostly
tsconfig.json), and definitely a build step. The compiled JS will also be more difficult to read than regular human-made JS, so you will want to configure sourcemaps.above I said Typescript is mostly the same as JS but with static typing. The "mostly" is because Typescript also has a few features which JS does not, e.g. decorators, enums, and maybe some others I can't remember right now. These all still compile into JS, just with generated code that does the equivalent of that feature.
huuaaang@reddit
Only use Javascript if you don't need a build pipeline and just want to write files that will be directly included in HTML frontends. Everything else should be typescript. It's just a good habit to get into as a professional. That and actually USE the type system and don't just put "any" everywhere.
acamann@reddit
JavaScript is like cooking in a kitchen with unlabeled jars, where you only realize you swapped salt for sugar once the customer sends the soup back. TypeScript labels every jar and acts as a sous-chef who taps your shoulder the second you reach for the wrong ingredient, catching the disaster before it ever leaves the prep station.
440Music@reddit
I think /u/PhiLho 's answer of "Limiting you intentionally" is important, even for your kind of analogy, because otherwise it sounds like an absurdity not to use typescript.
Perhaps an amendment like this:
"Conversely, if you realize a jar is not labeled correctly, the sous chef will not allow you to push out an order with the correct ingredient, even if you are in a time crunch. You will be expected to fix the label first. In this sense, you are limited by the labels. But chances are you'd appreciate the ruthlessly enforced label system over not having it at all."
acamann@reddit
Very good point
TheDeadlyAvenger@reddit
Nice anaology.
FX2000@reddit
If I’m the only one touching the code I’ll do JS, if it’s a team project then TS it is.
nightwood@reddit
Typescript has an extremely powerful system for describing exactly what values a parameter or (return)value may have. For example, if you have an integer that can only have values 0..3 you can do something like:
So when anyone wants to return a different value, you get an error.
Typescript is also amazing at figuring out wether code can be called and wether invalid values exist. It really prevents you from forgetting edge cases etc.
scoutzzgod@reddit
In the end, any .ts code will be .js code
It’s a way to improve DX (developer experience) in any codebase by providing static and strongly typed behavior to javascript. One that is neither of the two Â
Sufficient_Duck_8051@reddit
TypeScript is basically JS but you tell it what types your variables are, and it yells at you during development instead of silently breaking in production. doesn’t add new capabilities really, it’s more like a safety net for when your codebase gets big enough that you stop remembering what every function expects. for a small project honestly don’t bother, but the moment you’re working with other people or a complex data model you’ll be grateful. that said it’s still JS under the hood so..
Unable-Map-5351@reddit
Perhaps I haven't quite grasped it well enough, but as someone who also works with Java, I've struggled to use TS, as compared to JS. It just doesn't feel natural or intuitive when errors are raised, like mismatched types (between a method's parameters and the arguments I give in an implementation), for example. Many a time, I struggle to think in terms of types when I work with objects in TS.
But with Java, I feel like I'm able to understand backend code and its structure much better, as opposed to a dynamically typed language like JS or Python.
peterlinddk@reddit
This is probably the best answer!
For years I didn't get why TypeScript even existed, but somehow I stumbled upon an interview with creator Anders Hejlsberg (unfortunately can't find it again) where he explained that TypeScript was intended more for the tools (the IDE) than the developer - because defining all the types your code expected and returned, the IDE would be able to analyze your program, figure out if you are sending the correct objects, and prevent you from writing code that might fail.
And especially when working in a team, and you might not know exactly what it expected to be in a certain object, TypeScript also helps you, as the specification is part of the code.
BleachedPink@reddit
I'm just learning programming, but I realized that Typescript is cool, when I made a small change and my IDE instantly highlighted new issues in 8 different places I have to fix now.
Really cut down a lot of time figuring out where all the new bugs
Maleficent-Ad5999@reddit
The only capability TS adds in my opinion is the experimental decorators. Although they’re not widely adopted, I love it.
cheezballs@reddit
TS is for when you want to complicate your pipeline while being able to write code that is sort of OO and sort of statically types, but not quite. When TS first came out I thought it was great. Then I learned how to actually use JS and I've never needed TS since.
oscurochu@reddit
typescript compiles to JavaScript, and the compiled typescript is the code that actually runs. but if your code requires type safety, there are a few things you can do before you think about switching to typescript.
validate all your data. if you aren't validating your data, your type safety checks aren't going to work as expected at best, and not compile at all, at worst.
but if you are developing an application that requires type safety, like c++, typescript can provide a level of sanity of making sure your data is valid before your backend application ever seens any data
oscurochu@reddit
typescript compiles to JavaScript, and the compiled typescript is the code that actually runs. but if your code requires type safety, there are a few things you can do before you think about switching to typescript.
validate all your data. if you aren't validating your data, your type safety checks aren't going to work as expected at best, and not compile at all, at worst.
but if you are developing an application that requires type safety, like c++, typescript can provide a level of sanity of making sure your data is valid before your backend application ever seens any data
Visible-Employee-403@reddit
https://en.wikipedia.org/wiki/Type_safety
syklemil@reddit
Also for "handling types automatically" most of us prefer some sort of type inference.
Static typing used to involve a lot of keyboard typing and a ton of restrictions for sometimes marginal gains in type safety, like in C where it's practically more about helping the compiler do memory math than about type safety. (See also: "uncle" Bob's reminiscing about way-back-when C compilers would effectively ignore type errors, and his horror at Swift letting the programmer control nullability.)
There are still plenty of people who prefer untyped systems (lisp fans tend to be vocal in that direction), but they seem to be a clear minority at this point.
ShoulderPast2433@reddit
JavaScript doesn't control types in the way you'd really want as a programmer.
It makes program work somehow even when you made a mistake and consequences of production bugs are much more expensive than longer development caused by more boilerplated syntax.
It's a trade-off - faster writing vs riskier code.
MercyHealMePls@reddit
I would make the argument that TypeScript is actually faster on average in development too, due to better autocomplete and because you don’t have to look at the implementation/logic of a function to know what type to pass as parameter for example.
syklemil@reddit
Mm, programming languages that are very wibbly-wobbly about types seem to wind up being seen as easy to get started with, but hard to get right in bigger projects. Tracking just the time to first production deploy and not the amount of in-production bugfixes and oncall incidents will probably also skew perceptions.
At some point that kind of language also seems to introduce a
===to reduce the wibbly-wobbliness; anyone who'd generally prefer===over==should also have some intuition for why people would prefer TS over JS.patternrelay@reddit
TypeScript doesn’t add runtime power, it shifts failure earlier. In small scripts JS is fine, but as systems grow, implicit types hide coupling. TS makes those dependencies explicit so refactors break at compile time instead of in production.
port888@reddit
TS is a development tool. It makes the development work for apps that eventually run javascript much more ergonomic. When you define a function that takes in a number, then in another place you call that function with a string input, TS can help catch this bug before it ends up in production (the compilation step fails with error message, or the IDE might even catch it for you in-line). In JS, unless set up with JS doc in a supported IDE, you wouldn't know such a bug existed until your app crashed in prod.
code_matter@reddit
It controls typing. It enforces some rules and logic that you simply can’t force in JS.
It’s a GREAT tool to view your data in a “set theory” mindset.
elg97477@reddit
For small scale projects, where you can keep everything in your head m, use JavaScript. The overhead of introducing types isn’t worth it.
However, for large projects where you can no longer remember what every object structure is, typescript will save time.
Ultimas134@reddit
Typescript is largely used in testing. So if you wanted to write automated test cases.
AdityaVerma609@reddit
The main advantage of TypeScript shows up when your project scales. In JavaScript, you can pass anything anywhere and it won’t complain until something breaks. TypeScript forces you to be explicit about what kind of data your functions expect, which makes your code more predictable. It’s less about doing more and more about breaking less.
Taskdask@reddit
Typescript is your best friend when coding in JavaScript. I remember being skeptical towards it the first time I heard about it, thinking that it added bloat in the IDE that wasn't necessary. But then I joined a team that worked on a massive codebase, and the benefits of using Typescript were immediately obvious. Here are a few examples:
Basically, it's going to help you write better and safer code, help you spend less time debugging, and free up valuable working memory from your brain by providing real-time type checking and type definitions at a glance in your IDE.
I never write plain JavaScript anymore because Typescript essentially helps me be a better and more efficient developer.
AngryFace4@reddit
TS is “let’s make coding some rules to follow that will make our apps crash less at run time”
jibbit@reddit
typescript js an error checker for js. that's all. in can help you find errors. you can run it on any js to get an idea of the kinda things it considers dangerous. you can configure it to be more or less strict with what it will allow. at the stricter levels you have to add additional labels to your code to describe your intentions more precisely. ts will strip out these labels giving you back regular js. it's also fine to use it on the less strict settings
U4-EA@reddit
IMO JS should never be coded directly - it should only be produced from TS by running the TS compiler against it. This might help to explain the importance. https://www.reddit.com/r/typescript/comments/aofcik/38_of_bugs_at_airbnb_could_have_been_prevented_by/
Lumethys@reddit
if you have an object with 100 nested fields. Would you rather know exactly what each field's datatype is, instead of looking at 3000 lines of code to figure it out?
Alive-Cake-3045@reddit
TypeScript is basically JavaScript with type safety on top. It helps catch errors before running the code, which is super useful in larger projects or when working in teams. JavaScript can do almost everything TypeScript can at runtime, but TypeScript makes code easier to maintain, refactor, and debug by clearly defining what kind of data each variable or function expects. Great for scaling projects.
ExtraTNT@reddit
It’s js with types in case you want a worse type system… js has jsdoc with types… type script has some downsides, for enterprise projects with some libs you got upsides, but for most projects you are better of with js and jsdoc…
corpsmoderne@reddit
Typescript provide a reasonable type system. This gives you certain safeguards while coding, something that may not be immediately sensible in small project, but in larger project, it helps control complexity.
It's like seat-belts. Do you need them to go from point A to point B ? No. Should you use them? hell yes.