TypeScript things I wish I knew earlier

The four things weren’t clear to me when I started

Published 4 April 2022 - by Alvar Lagerlöf

About a year ago, I decided to try TypeScript. It seemed in demand, and I had previous positive experiences writing in typed languages. It turned out to be a good choice, but there are some things I wish someone had told me before I started.

If you're unfamiliar with TypeScript, it is a layer on top of JavaScript that specifies the type of things. You tell if a variable must be a string, or if an object must have the firstName and lastName keys inside.

No type checking at runtime

Before TypeScript, I had been using types with things like Java and Swift, which both have type checking built into the language. I knew TypeScript converted to JavaScript in the end, but I expected it would leave some type checking things behind. It doesn’t! There is no run-time type checking.

Upon first getting to know, I was confused. What was the point, then? Then I learned about compile-time type checking. Basically, the TypeScript compiler looks at your code before it runs in the browser or in Node, and checks to make sure everything lines up. There are other tools that do this, but with TypeScript and some of your own types to guide can become much smarter. You’ll often find errors before your code even runs!

Refactoring feels much safer

Due to the previous point, refactoring is easier. TypesScript keeps track of how code is being used and imported in multiple places. If you introduce a change in one part, it can tell you how other parts need to be changed for the code to work. As someone who easily gets distracted, this helps me remember to complete my refactoring adventures.

Prefer interfaces over types

In TypeScript, you can type JavaScript objects using type or interface. At first, I was confused about when to use each of these. The documentation was unclear. What I’ve landed on though is to use interface primarily. Interfaces do not have as many features as a type, so use them until it isn’t possible anymore. This seems to be the unwritten convention in TypeScript code.

You don’t need to use TypeScript everywhere

Unless you’re on strict settings, all JavaScript is valid TypeScript code. TypeScript can be sprinkled on top. Use this to your advantage. When converting code, everything does not have to be typed. You can do a bit at a time, or even completely leave parts out. This makes the process much easier and less time-consuming to switch.

These are my four things I wish I’d known before I started. What’s yours? I’d love to hear your tips here.