Typescript — The Basics

In the world of software development keeping up with new technologies can be difficult. You spend all this time learning some cool new feature or library then as soon as you feel confident in it you see a headline like this, “Is {insert name} the new {tech you just learned} killer? To avoid this I like to look at new job listings to see if I can find common patterns. What are companies actually looking for? Well, look at enough job postings and you will start seeing Typescript popping up all over the place, and rightfully so. I’ve been using Typescript professionally for the last year, let’s go over some of the basics.

  1. Types

Let’s take a simple JS function.

addTwo(2); would return 4

addTwo(“two”); would return “two2”

Just using vanilla JS we wouldn’t see this code until runtime. So unless you’re using TDD or checking everything as you go then you’re going to have a bad time here. Now let’s make it a TS function just by adding a type.

addTwo(2); still returns 4

addTwo(“two”); would give you a compile error basically saying that type string is not assignable to type number. This allows you to catch the error right away instead of going through testing with it.

2. Tuples and optional values

Tuples aren’t a TS-only feature. They can be found in other programming languages but they do not appear in JS so Typescript gives you the ability to use them. An example of a tuple can be found below

Written this way, if you don’t give all three values in the correct type then you will get a compile error. If you want to make the array valid without all of the elements then you can make one or more of the elements optional with a question mark. Like this:

This will accept a boolean, and only a boolean, value at the end of the array but it is not mandatory.

3. Using new JS features

Typescript is run through a compiler every time you save (as long as you set watch: true in your tsconfig.json file) your code. You can set your compiler to compile to any ES release you like. This allows you to use the newest ES features, have them compiled down to ES-3(default), or whatever, and not have to worry about compatibility.

4. Start slow

Any JS code is also valid TS code. Just change your .js files to .ts and you're good to go. No need to refactor any old code. Just start using any TS features you’ve learned and throw more in as you gain more knowledge.

5. IntelliSense and IDE features

Being strong-typed, Typescript comes out of the box with a great IDE experience. Features like IntelliSense give you completion hints, content assist, and documentation for errors.

That does it! There are many more features for you to investigate, the next two I would recommend are interfaces/inheritance and generics but this should be enough to get you writing your first TS code.