Learning TypeScript Fundamentals from Scratch (Part 1 — Installation and Hello World)
If I had to describe TypeScript in a few words, I would say something like this:
It’s Javascript that Java advocates will love!
It’s no secret that one of the characteristics that keep many developers away from the JavaScript world is its lack of strict types. But you may wonder: Why do we need types anyway? Are they indispensable? The answer will depend on whom you ask. If I had to respond, I would say…. mmm maybe.
Consider this javascript function:
function add(a, b) {
return a + b;
}
Nothing new here, this will add two numbers up, right? Not always! What if one of the parameters is a String, or maybe an object, or array, what about a potato. Will it work with a potato? Probably it won’t in the same way.
If the intention on the function above is adding two numbers and nothing else, we would have to include extra validations that can ensure that behavior. Otherwise, we might get some unexpected errors or undesired results.
TypeScript to the rescue!
The typescript language was born on the need to have a strongly typed JavaScript. As dull as it might sound, by pre-defining types in our code, we can have more control over it, and ensure consistency in any data result we get.
Let’s rewrite the past function using typescript:
function add(a:number, b:number):number {
return a + b;
}
Here, we predefine the data types for the incoming parameters, as well as the final return. By doing this, this function will always return a two numbers sum.
Nowadays, typescript is commonly used to develop Angular applications. But it’s entirely feasible to use it for developing React and Node applications as well. That’s why I consider it a tool we should learn more about. Let’s do it!
Installing the compiler and setting up a Sandbox Project
First, it’s necessary to install our typescript compiler using npm:
$npm install typescript -g
Let’s create a new folder. You can call it typescript-sandbox
or any other name you prefer. Move into that folder using cd
.
$mkdir typescript-sandbox
$cd typescript-sandbox
At this point, the tsc
command is already available, and we can use it to compile any typescript file (ts extension) we want. But let’s first initialize a typescript config file by doing:
$tsc --init
You’ll notice there’s a new file in our root project called tsconfig.json
. This file is used to configure compiler options so that we can avoid using the command line.
If you take a look at this file, you will notice several configuration options (most of them commented). Here, we’re going to apply some minimal changes:
- Change target value to
“ES2016”
to use ES7 features. - Uncomment
"noImplicitAny"
to get an error when anany
type is detected. - Add
“noEmitOnError”: true
to avoid compiling in case of error. - Add
“outDir”: “./dist”
to output the compiled files into a “dist” folder.
In the end, this tsconfig.json
file should look like this:
Hello World class
At this point, we should be able to compile a .ts
file. We can do it by just typing tsc
on the terminal. So let’s create a typescript class that will log a “Hello World” from its constructor. We can define this class inside a main.ts
file or any other name you prefer.
class HelloWorld {
constructor(name: string) {
console.log(`Hello ${name}`);
}
}new HelloWorld("World");
As you can see, this class is taking a string parameter into its constructor (“World”) and logging a hello message inside of it. Let’s compile this by typing tsc
on the terminal. We should be able to see a new dist folder with a main.js
file inside of it with the following content:
"use strict";
class HelloWorld {
constructor(name) {
console.log(`Hello ${name}`);
}
}new HelloWorld("World");
The compiled JS file is very similar to the typescript file, which makes sense since we set ES2016 as target version in our tsconfig.json
, so JS classes are available to use.
If we change the target version to an older one (ES5), we will notice — after compiling again — a significant difference:
"use strict";
var HelloWorld = /** @class */ (function () {
function HelloWorld(name) {
console.log("Hello " + name);
}
return HelloWorld;
}());
new HelloWorld("World");
As you may know, ES5 doesn’t support JS classes. So the compiler will always use function prototypes instead.
Finally, to run this code, we can use the node command line:
$node dist/main.js
We need to run the compiled file, not the typescript one. Our node environment will run it correctly since we set commonjs as module generator. Thus, any “import” statement will be correctly translated to “require.”
If you don’t want to always write tsc
on the terminal to compile the code, I recommend to run the compiler on watch mode by doing:
$tsc --watch
Now any time you make changes, a new JS compiled file will be generated.
That’s it! Our typescript sandbox is up and running. I invite you to read the second part of this article to learn more about the typescript syntax.