laptop

Should you use TypeScript instead of JavaScript?

laptop
What are the benefits of TypeScript? In this article, I will show you with examples how TypeScript can improve your productivity (and your sanity).

What is TypeScript?

Open-sourced programming language created by Anders Hejlsberg from Microsoft. This is the same guy which created the C# language.

TypeScript is a superset of JavaScript. So what does that mean? If I google superset, I get mostly hits of bodybuilding sites! What!? Relax, no need to lift heavy weights. In this case, a superset means that you can paste plain JavaScript code into TypeScript, and it will work. But since it is a superset, it means it can do other cool stuff as well, which we will discuss later in this post.

It is called TypeScript, so it shouldn’t come as a surprise that types are supported in the language. These types are optional, but adding types can make your life a lot easier.

What is JavaScript?

JavaScript is a dynamically typed language. This means you can’t explicitly add types, but JavaScript will assign the types in runtime.

There are different versions of JavaScript which you need to be aware of.

ES5

This is the version which is supported by all the browsers, so the majority of the JavaScript in the world is coded in this version.

ES6

Added new features like classes, arrow functions, etc.

Supported by most of the leading browsers. But Internet Explorer does not support it. (Hopefully, that browser will vanish for good soon). Since you want your application to work for most people, you should translate the code to ES5. You can do that by using a transpiler tool like Babel.

What can TypeScript do which JavaScript can’t?

TypeScript support all the latest versions of JavaScript, including future features.

Types

TypeScript support Types. JavaScript does not.

Interfaces

If you have a C# background, you are probably used to interfaces.

In TypeScript, you will probably use it a little different. The interface will describe a type,

This means if you have a person object, you can define an interface with, name, age, address, etc. And if you then assign the person object with that interface, you will get IntelliSense only on the properties you have defined. If you try to use something else, your IDE will throw an error. This is a dream because you don’t need to guess what the person object comprises of.

What are the reasons to use TypeScript?

Intellisense

With a strongly typed language like TypeScript, we get precise Intellisense. This is a considerable advantage over JavaScript.

Here you see a typical section of TypeScript code. We have an interface which describes what a person object contains. When we use that object, you know that we only get the properties which we have defined.

Typescript intellisense

Since JavaScript is a weakly typed language, it doesn’t know what to look after. Some IDE’s tries to give some intellisense by guessing. This is very difficult for the IDE to do, so it just gives you everything it knows, like in this example:

javascript intellisense

By working with types, it is easier to work with a larger team. When having return types and types of all the parameters, you give other developers more information to understand what your function does.

So what about third-party libraries? Well, there is declaration files. These are TypeScript files which only contains interfaces which describe the API’s. This means you don’t have to look up the documentation all the time when working with the libraries, but instead figure things out by using intellisense.

Here is an example where I have loaded types from the lodash library. I might know there is a random function in the library, so I start typing in “ra”. As you can see, I get a list where there is a random function. Not only that, I can see what the function returns, what types the parameters has, how many overloads there is and a detailed explanation! Can you see how useful this can be?

Typescript intellisense lodash

Reveals mistakes during development

With JavaScript, you won’t get much notification on typos during development. This is easily missed, and you most likely will discover these kinds of bugs during runtime. Worst case, it will be discovered by one of your users, and you can say goodbye to that weekend at the cabin.

Here you can see a simple mistake where we misspelled “person.lastname”. This will output “Jim undefined”.

I know this is a simple example, but within a big project, it might take hours finding and correcting the bug.

javascript spelling mistake

However, in TypeScript, if you have used the optional types and interfaces, you will get a red squiggly in the IDE, and the compiler will throw an error.

Like this:

Ah, Much better!

This doesn’t mean that TypeScript will make your code bug free, but it will weed out those annoying typo mistakes.

Use tomorrows ES features today

TypeScript is always using the latest ES version plus planned feature in a future version. This is possible since TypeScript is transpiling these future features into ES6 or ES5. In other words, you will always have access to the latest and cutting edge in JavaScript.

When you are coming from a typed language

If you have a background from C# or Java, you probably get a little shocked when you are getting into JavaScript. For those developers, it is much more natural to work with TypeScript. Remember the creator of C# was also the creator of TypeScript, so there are a lot of similarities here.

That being said, you should still learn plain ES5 JavaScript. It is a language which has enormous usage in the world, and you will most likely work with it in one way or another. So spend time learning the ins and outs of JavaScript. It is well worth it.

Are there reasons to use JavaScript instead of TypeScript?

Small projects

If you are creating a tiny project, I think it would be ok to just use JavaScript, as long as you don’t have to do much updating or expanding later.

In those cases, you don’t need to create a build system with typescript, source maps, etc. It is faster to just hack out some javascript code.

Declaration files

Like I mentioned earlier in this post, third-party libraries have declaration files which describe the APIs for the library. This is great for just using intellisense on what kind of methods and properties that exist.

You must make sure though, that the declaration file and the actual library have the same version. Or else you might get unexpected compilation errors.

Also if you are using an obscure library, there might not be any declaration file at all. Then you are stuck writing the declaration file yourself or doing other hacky solutions.

Learning curves

There is a little bit of a learning curve if you are used to plain ES5.

Since it is a superset of JavaScript, I think the learning curve is pretty low. You can copy and paste the code from the js file and just add types at your own pace.

There are some considerations you need to do by setup build tools, install TypeScript, etc. These are things you didn’t have to do with a plain JavaScript project.

Basic setup in VS Code

Here are six steps for setting up VS Code with TypeScript. VS Code is a great IDE from Microsoft. You will also need to install NodeJS to run the code from the terminal.

Step 1 – Open VS Code in an empty folder

Create an empty folder on your hard drive. Open up VS Code and choose “Open folder…”. Select the empty folder you have just created.

Step 2 – Install TypeScript

In VS Code, open the integrated terminal and enter the following:

npm install -g typescript

This will install typescript on your machine. You need this to transpile the TypeScript code to JavaScript.

Step 3 – Add tsconfig.json file

This file will tell TypeScript how it should transpile the code.

I have just added two basic properties here. Target means which JavaScript version TypeScript should transpile to. SourceMap is an extra file which helps you to debug the TypeScript code.

{
    "compilerOptions": {
        "target": "es5",
        "sourceMap": true
    }
}
Step 4 – Add an app.ts file

Create a new app.ts file, and add this code:

let text = "Hello World";
console.log(text);
Step 5 – Start build task for automatic transpiling

In this step, we will generate an automated task. This task will transpile your TypeScript code to JavaScript everytime you save your file.

Choose “Tasks: Run Build task” (CTRL + SHIFT + B on Windows, ⇧⌘B on Mac)

Then choose “tsc: watch – tsconfig.json”.

This is it. Save the code, and it will automatically create an app.js file. This file has been transpiled to es5 since we did set that in the tsconfig.json file. You can verify that by looking in the app.js file, and you can see it changed “let” (which is an ES6 feature), to “var”.

Step 6 – Run the app with Node

Make sure you have installed NodeJS. Type “node -v” in the terminal. You should get a version number if correctly installed.

Type “node app” to run the app, and you should get “Hello World” as an output.

Conclusion

I hope you in this post have learned something about the benefits of using TypeScript and that you might be implementing it in your projects.

TypeScript has been more and more popular the recent years, and big frameworks like Angular are embracing TypeScript.

I think features like better intellisense and error-checking during development are fantastic features, which makes my life more comfortable as a developer.

Similar Posts