TypeScript: a beginner setup

TypeScript, the super set of JavaScript, that makes JavaScript itself more similar to the back end object oriented programming languages. The TypeScript commands have to be compiled and the output will be a pure JavaScript code. A watcher will be implemented in order to compile the TypeScript files every time the file is modified.

In the newly created folder first-typescript, let’s execute npm init command, leaving all the configuration fields as the defaults and confirm. Let’s create the entry point file index.js in the root folder and its content:

require('./tasks/watch-ts')

We need to create now the app folder where we’ll have the TypeScript (and the compiled JavaScript) files. We need also the tasks folder and the watch-ts.js file in it. Its content is:

Before testing it, we have to install the required packages:npm install watch npm-run colors

Every time a TypeScript file in the app folder is edited, the watcher will trigger the tsc (TypeScript compiler) command execution.

If you did everything correct you should be able to run the following command without having any error messages in the console:node index.js

While having the node index.js command running, in the app folder let’s create a TypesScript file (just a text file having .ts exention) and add the following code into it:

functionf(n: number) {
}
f('x');

If we look at the console we will see a red line, telling us that something went wrong. The error message is self-explanatory. We called the function passing a string as input parameter, while the function signature tell us that the expected input parameter should be a number. We can just change the function call into f(10) to make it working, with no errors in the console. Note the JavaScript file been generated in the app folder. Thanks to TypeScript we can now use, for instance, strongly typed data.

This article was written to give you a starting point to let you deep dive into the powerful TypeScript language. For more about its features please refer to the documentation.

Professionals accustomed to the traditional object-oriented approach, with languages ​​like Java, C ++ or C #, suffer the transition to JavaScript due to the absence of data type management.

The challenge posed in these terms, however, is not correct, since JavaScript is a typed language, but that does not provide static controls on data types and makes an implicit conversion between types (dynamic type-checking).

This feature favors the enormous flexibility of the language and is probably one of the keys to success of JavaScript, however the absence of type checks during compilation (to “compile time”) can generate errors that are difficult to analyze at runtime.

To fill this gap, Microsoft implemented a JavaScript extension in 2012 that adds support for static type checking and other features designed to write complex applications: TypeScript.

The advantages of TypeScript, in practice
TypeScript is an extension of JavaScript and any JavaScript script is also valid TypeScript code. This simple observation already offers us many advantages in the adoption of TypeScript for our next projects.

The first advantage is offered by the fact that the transition from an existing JavaScript project to TypeScript can be done gradually, without the need to rewrite everything.

The second advantage is represented by the possibility of exploiting the TypeScript compiler on standard JavaScript code to identify errors that can normally be missed during compiling. Consider the following JavaScript code:

An expert programmer at a glance identifies errors in this code, but it is not infrequent that some error escapes and we notice it at runtime or, worse, we get unforeseen behaviors and difficult to diagnose.

If we insert this code in the Playground TypeScript window we will see some interesting messages before we even run it:

The compiler will report us the duplication of the name property for the user object, the absence of the new operator before Date(), the assignment of a null value to document.onload instead of a function, the nonexistence of the getElementByID() method for the document object. These time-based controls save valuable time and help create more robust code.

These instructions will not generate an execution time error, despite our attempt to execute … the square of a string!

This is completely legitimate code from the point of view of JavaScript whose result will be the assignment of the NaN value to the variable y. For this reason, even the TypeScript compiler will not report any anomaly.

However, almost certainly, these were not the intentions of those who wrote the code. The square() function must be an operation that only applies to numbers. To prevent the unauthorised use of values ​​other than numbers we have two possibilities:

Add JavaScript code to the function that parses the data type of the n parameter before performing the operation.
Exploit TypeScript and declare the data type of the parameter.

The second approach involves adding an annotation alongside the parameter of the square() function, as shown below:

This is by far a better solution than the first one because it avoids us writing additional code and allows us to find out, at compile time, any unauthorised uses of the square() function. In fact, the compiler will notify us immediately that we can not pass a string to the function.

Just a simple example like this to understand how TypeScript actually turns JavaScript into a strongly typed language making it suitable for the development of applications of a certain complexity.