Why You Should Learn Typescript

Rick Moore
Nerd For Tech
Published in
7 min readAug 22, 2021

--

Photo by Celine Nadon on Unsplash

Having been swimming around the coding ecosystem for some time now, I have a list of technologies that I’ve heard about over and over, but never sat down and absorbed. TypeScript is high on that list, and this week, I had a chance to drink the Kool-Aid.

I’m a JavaScript/React developer, and I’m always trying to read docs and work through courses in my free time to keep my skills sharp and up to date with current technologies. I took a common project from a Udemy.com React course, and decided to follow along, but to build my version using NextJS and TypeScript, instead of vanilla JavaScript/React. This gave me a real world playground to work out the basics of TypeScript, and I quickly caught on to the huge benefits its brought to my workflow.

I want to show you a few of the roadblocks I hit while learning the basics, and share some of those “Oh heck yes!” moments I had, and explain why I don’t ever want to go back to not using TypeScript.

Declaring Variables

If you’re completely unfamiliar with TypeScript, it is a superset of JavaScript, meaning its features are largely optional, and all valid JavaScript is already valid TypeScript. That being said, essentially, Typescript allows you to use strongly-typed variables, similar to C or Java. This means that when you declare a variable, you also declare what type of data that variable should hold.

The syntax for declaring a variable is straightforward, and uses the types we are used to from JavaScript.

<declarative> <variable name>: <type> = <data>

Typescript Basic Variables

In TypeScript, once the variable has been declared, its type cannot be changed, and data of a different type cannot be assigned to that variable. If we tried to assign the variable num to the string '10', TypeScript will throw an error.

Wrong Type Error

Here, the compiler knows that num should be a number type, and says “hey, I can’t assign a string '10' to that!” I go back and think of all the times that I’ve dealt with data from DOM elements, for example, and written Redux actions never knowing for sure if I was getting number strings or actual numbers, and always needing to manually cast my data into the type I needed to satisfy cryptic errors. This tedious exercise becomes much less agonizing when your compiler is automatically checking the data type for you.

We can also declare arrays and objects.

Following a type with the brackets [] indicates an array filled with the specified data type. For our arrayOfNumbers here, we couldn’t add another element to the array that’s not of the number data type.

Numbers Array Error

Same thing with our employee variable here. We’re telling the compiler that this variable should be holding an object, and only have the name property, a string, and an age property, a number, and nothing else. Trying to add another property will throw an error.

Object Error

At the same time, when it comes time to reference our employee object, we now get intellisense suggestions that tell us exactly what we’ve declared the object to contain.

Intellisense on Object

Hopefully you already get a sense of how useful these new errors can be. It took some time to get used to, but now I just instinctively want to know, conclusively, what data type a variable is. TypeScript brings us that assurance during development, before build time.

Interfaces

So, we can make our data types clear when declaring a variable, but what about when things get a little more complicated. Most of the time, we’ll want to use objects from a database, that may have many data types and nested data included. How do we handle more complex objects?

We have a new tool in our belt from TypeScript called an interface. Now you may think at first glance that an interface looks a lot like a class, and you are right, but they have some clear differences.

  1. A Class is a logical block of code intended to be reusable and build instances of objects based on a prototype.
  2. An Interface is a contract with our code. A set of rules that can be checked and referenced to ensure the integrity of the data in an object. Interfaces cannot create objects, but can check an object to ensure it meets a set of standards.

I’ll use an example from the project I’m currently working on. In this project, we have raw color data that gets organized into Palette objects. I created this interface to check my palette objects for correctness:

Now I can reference this IsPalette type in my variable declarations as a data type. If something about an object doesn’t meet the requirements of this contract, TypeScript will let me know. Let’s take some seed data and put this interface to use:

Based on the interface I imported, any deviation from that schema will throw an error and need to be corrected before the code will compile.

Now, a question I had was around unknown data, or building objects one part at a time, because you need to fit the interface exactly to avoid any errors. We have a few useful tools to help us with this. first is the any type. You could always use this to tell the compiler that the code should allow any type to be assigned to that variable.

I needed to take my palettes that I had built, and adjust them a bit to create a new, fancier palette through a set of helper functions. So I created an intermediate interface, and a final interface to check my data along the way.

I need to get my data to look like this:

However, I needed to build a palette, then add in the colors data piece by piece. If I used this interface as a data type, I would be getting errors because of the incomplete data.

So my generatePalette function here takes in an argument of starterPalette, which is of type IsPalette (my original interface). The function is then returning an object of type IsChromaPalette which includes all the data we’ve added in the function. I needed to create an object to build on, and used the IsNewPalette type to verify the initial information, and left the colors property open using the any keyword.

Again, the beautiful thing about this extra work of declaring these types, is that many of the human errors are caught quite early in development. In fact, Because I was using TypeScript, I caught several errors that the instructor missed as I was creating my version of the project.

DOM Interaction

I ran into an error that I didn’t understand at first, while trying to set up a package with a slider for color selection in my project. I eventually realized that the TypeScript error was telling me exactly what I needed to do and saved me from what would be a debugging session later.

I knew that this new component had a onAfterChange property, but I didn’t know what was going on under the hood, or what this property was passing into the callback. I assumed it was a standard React Synthetic Event, and I treated it as such, but I kept getting an error when it was set up this way.

Again this is WRONG, as I kept trying to treat the argument coming from onAfterChange as an event, which it is most definitely not. And even though I didn’t know at the time, the error message tells me exactly where I screwed up:

Slider Error

Essentially, this is telling us that the onAfterChange attribute is trying to pass an argument to the callback called value with a type of number and I am being dense by expecting a SyntheticEvent. Okay, now that we understand that we are expecting a value argument of type number we can fix this!

Alright! No errors and everything works. We know that we’ll be receiving a number from onAfterChange and we can use this to directly set our state, which will select the color on the component.

Once again, I could have managed to get the code to work without all of these type checks, but being certain of the data early on saved me a ton of debugging time later on.

Conclusion

I think the best part of TypeScript is that it’s optional, and a superset of JavaScript, which makes it easy to slowly implement its features as you learn them, or use it only in places that would benefit from type checking.

Personally, consider me converted. I’ll find excuses to use TypeScript anywhere I can and annoy people at parties by constantly talking about how great it is.

Thanks for reading this far and happy coding!!

--

--

Rick Moore
Nerd For Tech

Software Engineer at Thrive TRM. Specializing in Ruby on Rails, React/Redux and JavaScript.