The TypeScript language

For the last 5 or 6 years, there has been a growing hype around the languages used to build websites and web applications. As you surely know, the reason was mainly related to the proliferation of mobile devices of all types: tablets, phones, IoT devices, and so on.

Parallel to this, back in 2008, a new effort for standardization emerged at the W3C (http://www.w3.org, the entity that takes care of most of the Internet language's specs) in order to update these languages of the Web and make them more suitable for this decade's needs. Announcements like the elimination of Flash components (or Silverlight, for that matter) on platforms such as MacOS or iOS only fostered these attempts.

For the first time in many years, a bunch of companies invested in the creation of this new Open Web that would be capable of holding any kind of content in a flexible, adaptable, easy-to-use, and responsive way.

All these efforts came to an end in 2015, with the final recommendation of HTML5 (https://www.w3.org/TR/html5/) along with a number of specifications related to the CSS3 presentation syntax (it's not a language, remember). They adopted a most-needed approach in the writing and testing process, starting with those whose implementation was a due requirement, such as Media Queries (very important in mobile devices, as you know).

Finally, the expected new version of the JavaScript language was published by ECMA (http://www.ecma-international.org/) and it received the name ECMAScript 2015 (previously named ES6 in the specification and testing processes).

Important decisions were taken in the creation of the HTML, CSS, and JavaScript standards: preserving backward compatibility, applying good practices and principles (such as the S.O.L.I.D. principles), and above all, making these specifications a continuous process of development and integration, for which the consensus of companies is key. So, after this first release of the specifications, the work continued in all these areas, except now, engineers of the main user agents' manufacturers collaborated directly with W3C and ECMA in order to make the HTML, CSS, and JavaScript engines faster, more reliable, and up to date. The most evident applications that came up as a result are generally called modern browsers.

The new JavaScript

So, a new JavaScript was born, which included many of the features that were long awaited by developers, such as classes, interfaces, scope variables, packages (finally, the concept of namespace shows up in the language, eliminating the need for closures), and many more.

Along with the new requirements, a set of libraries (a big one, by the way) appeared to help the developer in their daily tasks (they're numbered by hundreds, of thousands today).

As a consequence, the JavaScript language appeared to be the number one preference according to quite a few developer surveys carried out last year. One was carried out by the most popular code reference website among developers today: StackOverflow, which researched and published it with quite insightful results; you can read it at http://stackoverflow.com/research/developer-survey-2015.

The poll is very wide and covers a lot of different aspects, with thousands of developers having participated. The following figure showing the language's ranking is pretty important:

The new JavaScript

All this is great, but support for these features in browsers immediately became an important issue. Actually, support is insufficient and only a few browsers (the modern browsers, which we mentioned earlier), such as Chrome's latest versions, Microsoft Edge, and Firefox's recent updates, give enough coverage of the great amount of news and functionality proposed by the new standards.

To make matters even worse, versions of the same type of browser are not coincidental, since they might depend on the device we use to open a website. In order to finalize the list of problems linked to this situation, developers started to build big applications in which, not just dozens or hundreds but several thousands of lines of JavaScript were required.

So, the need for a new tool to build these sites and applications arose, and—once again—our admired Anders Hejlsberg decided to do something serious about it. The solution he proposed is called TypeScript.

TypeScript: a superset of JavaScript

So, what's TypeScript and why is it a solution for these problems? The first question is answered on its own site at http://www.typescriptlang.org/. TypeScript is, as the ineffable Wikipedia states:

Typescript is a free and open source programming language developed and maintained by Microsoft. It is a strict superset of JavaScript, and adds optional static typing and class-based object-oriented programming to the language. TypeScript may be used to develop JavaScript applications for client-side or server-side (Node.js) execution.

And, how does TypeScript achieve these goals? Again, Wikipedia reminds us that:

TypeScript is designed for development of large applications and transcompiles to JavaScript. As TypeScript is a superset of JavaScript, any existing JavaScript programs are also valid TypeScript programs.

TypeScript: a superset of JavaScript

So, we can start writing or use already existing JavaScript, knowing that it will be 100% compatible with older browsers. However, the term transcompiles requires a bit of explanation. Since JavaScript (any version of it) is an interpreted, functional language, the one in charge of its execution will always be the JavaScript runtime embedded in the browser or user agent.

So, transcompiling (or just transpiling, like most people call it) is the process of converting TypeScript code into pure JavaScript that can be interpreted correctly by browsers. The advantage is double: on the one hand, we can decide which version of JavaScript we want (JavaScript 3, 5, or 2015), and on the other hand, when used with a tool such as Visual Studio (or even Visual Studio Code, Emacs, Vim, Sublime Text, and Eclipse via a plug-in provided by Palantir Technologies, and so on), we'll get all the benefits of Intellisense, code completion, dynamic analysis, and so on.

Indeed, once those tools are configured, they can use Roselyn services to supply Intellisense, type inference, and all the goodness we all know and love from other languages. By convention (although it's not mandatory), TypeScript files have a .ts extension.

So, what exactly is TypeScript?

The official answer to this question is that it is a superset of JavaScript that transpiles (generates after compilation) to valid JavaScript for whatever version you want to support: 3.0, 5.0 of ECMAScript 2015.

Furthermore, it allows you to work with features that won't be available until the next releases of the specification or—even if they are—features that are not yet supported in the majority of browsers.

Besides, the language starts with JavaScript, so any piece of JavaScript is also valid TypeScript. The big difference is that you work with a language that offers generally the same type of editing and compiling services that we've seen in this book related to Roslyn in particular: code completion, peek definitions, type checking, refactoring, code analysis, and so on.

Main features and coalitions

Another main feature is that the project was built to comply with any browser, any host, and any operating system. Actually, the TypeScript transpiler is written in TypeScript.

To summarize, the two most important characteristics that this architecture provide are as follows:

  • A whole set of tools enabled by static types
  • The possibility of using features in the future, with the confidence that the resulting code will work in every browser (or server).

With all these possibilities, a joint venture between Microsoft and Google appeared (to be precise, between the TypeScript team and Google's Angular Team) to work together in the new versions of Angular (2.0+).

Installing the tools

As always, we recommend that you download and install the latest version of the library, which is accompanied by some project templates. These templates cover the use of TypeScript with Apache/Cordova, with Node.js, or plain HTML.

You will find the latest version of TypeScript by searching for its name in the Tools/Extensions and Updates menu. There's another way to install it, by visiting the official site for the language located at https://www.typescriptlang.org/, which also contains extra documentation, demos, and a REPL to test code snippets online.

The current version that I'm using in this book is 1.8.4, but most likely, by the time the book is published, you'll have access to versions higher than 2.0. After accepting to download the installable file, you'll be presented with a confirmation dialog box like this:

Installing the tools

If you want to try a more complete and self-explanatory test of TypeScript, you can create a new project named HTML Application with TypeScript which you'll find in Templates/TypeScript after the previous installation.

The execution generates a web page, which shows a clock that changes the time every second. The review of the code structure is very informative:

class Greeter {
  element: HTMLElement;
  span: HTMLElement;
  timerToken: number;

  constructor(element: HTMLElement) {
    this.element = element;
    this.element.innerHTML += "The time is: ";
    this.span = document.createElement('span');
    this.element.appendChild(this.span);
    this.span.innerText = new Date().toUTCString();
  }

  start() {
    this.timerToken = setInterval(
      () => this.span.innerHTML = new Date().toUTCString(), 500);
  }

  stop() {
    clearTimeout(this.timerToken);
  }
}

window.onload = () => {
  var el = document.getElementById('content');
  var greeter = new Greeter(el);
  greeter.start();
};

As you can see, the app.ts file is defining a class (Greeter). The class has a state, defined using three fields, two of which relate to the user interface, so they are created as HTMLElement.

The constructor method is in charge of the initialization. It gets an HTMLElement argument and creates a new <span> element next to it in order to display the time every second after reading it from the system's time. The value is assigned to the innerText argument of <span>, so it shows the current time from the beginning.

Then, we have two methods: start() and stop(). The first uses a lambda and assigns the value of the timerToken field to a setInterval method, which receives a function to be called periodically. The return value is useful if you want to cancel the process at anytime, as we will do in slightly modifying the demo.

The result is shown in the HTMLElement interface linked to it; note that only one element in the user interface is involved: a div element with its ID content.

The mechanism that turns on the clock is expressed after the definition of the Greeter class. In the onload event, the content element is linked to a new instance of the Greeter class.

Note

To summarize, the class' purpose is to define a behavior and associate that behavior with a part of the user interface.

We can stop the clock simply by including a button (or any other HTMLElement interface) and making a slight change in the TypeScript code:

<button id="btnStop">Stop Clock</button>
window.onload = () => {
  // This links the UI to the JS code
  var el = document.getElementById('content');
  var btnStop = document.getElementById('btnStop');
  var greeter = new Greeter(el);
  // Now that Greeter is defined, we can use it
  // from the button to stop the clock
  btnStop.addEventListener("click", () => {
    greeter.stop();
    alert("Clock Stopped!");
  });
greeter.start();
};

Since stop() is already defined, there's no need to change the Greeter class. We assign a call to the stop() method to the button's click event, and that's all that is required:

Installing the tools

Transpiling to different versions

Visual Studio gives us the option to choose which version of JavaScript will be generated after the process of transpilation. You just have to go to Project | Properties and select the TypeScript Build tab. You'll learn how you're offered several options on how you would like the transpiler to behave. One of them shows a ComboBox with the available final JavaScript options.

Also, note that other options are available on JSX, managing comments, combining JavaScript, and so on in the way shown in the following screenshot:

Transpiling to different versions

A comparison of both files (.ts and .js) will make it clear how neat and concise (and object-oriented) the TypeScript code is in relation to the pure JavaScript.

However, the benefits don't end there. This is just the beginning, since most advantages are related to the creation process in the editor, Intellisense, type inference, and the like...

Advantages in the IDE

When we pass the cursor over a definition of the previous code, observe how every element is recognized by its type: the class itself and its members:

Advantages in the IDE

It's not just about recognizing the initialization values. If we change a member's value in the code and assign it to a different (non-compatible) type, the IDE will complain about this circumstance again:

Advantages in the IDE

Even within HTMLElements, you can find this kind of Intellisense, since a walk over the innerText property of the span element will tell you that the property is a string value.

To end with this example and change the functionality so that we can stop the clock, we only need to add any suitable element in the UI and assign it a call to Greeter.stop(), for example, with the following code to the HTML file:

<!-- Button to stop the clock -->
<button id="btnStop">Press to stop the clock</button>

In the TypeScript code, the following is the window.onload assignment:

var theButton = document.getElementById('btnStop');
theButton.onclick = () => {
  greeter.stop();
  theButton.innerText = "Clock stopped!";
}

Just for the sake of completeness, I'm including the whole code of the TypeScript file after the proposed modification:

class Greeter {
  element: HTMLElement;
  span: HTMLElement;
  timerToken: number;

  constructor(element: HTMLElement) {
    this.element = element;
    this.element.innerHTML += "The time is: ";
    this.span = document.createElement('span');
    this.element.appendChild(this.span);
    this.span.innerText = new Date().toUTCString();
  }

  start() {
    this.timerToken = setInterval(() => this.span.innerHTML =
    new Date().toUTCString(), 500);
  }

  stop() {
   clearTimeout(this.timerToken);
  }
}
window.onload = () => {
  var el = document.getElementById('content');
  var greeter = new Greeter(el);
  greeter.start();

  var theButton = document.getElementById('btnStop');
  theButton.onclick = () => {
    greeter.stop();
    theButton.innerText = "Clock stopped!";
  }
};

This will work like a charm. So, we can follow the OOP paradigm, create classes, define interfaces, and so on and still be working with pure JavaScript.

A note on TypeScript's object-oriented syntax

In this basic demo, the Greeter class is defined using the new class keyword available in ECMAScript 2015. You can declare a state for the class by defining its members, followed by the corresponding type—either it is another type (such as an HTMLElement) or a primitive type, such as number.

The constructor gets the element passed to it, assigns it a text, and creates a new span element that will be the receiver of every new string the start() method generates in order to update the current time. Once that span is initialized, the preliminary state of the class is ready to start working.

Later, two methods are defined: one to start the clock and another to stop it. Note that the clock is implemented using the setInterval function of JavaScript. The way to stop the interval process from keeping on running is by using a reference to the return value of that function. This is why timerToken is part of the class.

Also, observe the declaration of the callback function passed to setInterval, since it is another lambda expression, which creates a new string containing the current time every half second.

There's another important thing to note. How does the demo work if there's no app.js file yet? Well, if you press the Show all files button in the Solution Explorer menu, you'll see that an app.js file has indeed been created, and prototype inheritance has been used to define the functionality, only that it's been created using the JavaScript 3 syntax, thus allowing older browsers to work with it without incompatibilities.

More details and functionality

Up to this point, we've seen another approach to programming, this time, linked to the browser's universal language. With TypeScript, Microsoft takes a major step forward in covering its ecosystem of languages, and many companies are adopting it as an advanced solution that allows programming today with tomorrow's languages, as proclaimed by its slogan.

In this introduction, our purpose was only to present the language and its main features and integration with Visual Studio. In Chapter 8, Open Source Programming, we'll cover more aspects of the language so you can have a better idea of its possibilities.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.170.134