If you’re a web developer familiar with the ever-changing frontend landscape, you’re likely to have heard of TypeScript by now – “but what is it and why use it?”, we hear you cry.
What is it?
Why use it?
There are many reasons, with static typing being the flag-bearer. Static typing allows you to reason more confidently with your code and the code of others, reducing cognitive load. Explicit types also empower IDE tooling, giving you hints, warnings, and errors while you type.
A simple function that capitalises the first letter of every word in a string. It works as expected when we pass in a string – but if we were to pass in a non-string, there’d be no warning. In fact, we wouldn’t really know until runtime.
We don’t like runtime errors. Runtime errors can stop an entire web app from working, they’re often unhelpful and difficult to trace, and they tend to be difficult to reproduce.
Let’s look at the same example in TypeScript:
Spot the difference? Not much changed – we just specified some types. The function now explicitly requires a string as an argument, and explicitly returns a string. The closure we passed into map does the same.
Our TypeScript version works as expected when we pass in a string, but, if we were to pass in a non-string, we’d get an error at compile time. Before anything’s made it to production.
Is that it?
Nope, not even close – but in summary, the biggest additional benefits (in our opinion) are briefly summarised below.
TypeScript allows us to write code that we can confidently scale and refactor, while lowering the cognitive load required to write it. We can focus more on the bigger picture – like architecture and structure – when building applications, without having to worry so much about the smaller implementation details.