Getting started with TypeScript classes

This blog is a part of my TypeScript series, and the previous ones are:

1. Why program in TypeScript
2. Structural vs nominal typing

In the next several blogs, I’ll focus on object-oriented features of Typescript – classes and interfaces. Let’s start with classes.

First of all, let me remind you that starting from the ECMAScript 2015 spec (a.k.a. ES6), JavaScript supports classes. Being a superset of JavaScript, TypeScript supports all features from JavaScript classes and adds some extras.

For example, JavaScript doesn’t offer syntax for declaring class properties, but TypeScript does. In the screenshot below on the left, you can see how I declared and instantiated the class Person that has three properties. The right side shows the ES6 version of this code produced by the TypeScript compiler:

As you see, there are no properties in the JavaScript version of the class Person. Also, since the class Person didn’t declare a constructor, we had to initialize its properties after instantiating. A constructor is a special function that’s executed only once when the instance of a class is created.

Declaring a constructor with three arguments would allow you to instantiate the class Person and initialize its properties in one line. In TypeScript, you can provide type annotation for constructor’s arguments, but there’s more.

TypeScript offers access level qualifiers public, private, and protected (I’ll cover these in the future blog), and if you use any of them with the constructor arguments, the TypeScript will generate the code for adding these properties in a JavaScript object as in the following screenshot:

Now the code of the TypeScript class (on the left) is more concise and the generated JavaScript code creates three properties in the constructor. We’d like to bring your attention to line 6 in the above screenshot on the left. We declared the constant without specifying its type, but we could have re-written this line explicitly specifying the type of p as follows:

const p: Person = new Person("John", "Smith", 25);

This illustrates an unnecessary use of an explicit type annotation. Since you declare a constant and immediately initialize it with an object of a known type (i.e. Person), the TypeScript type checker can easily infer and assign the type to the constant p. The generated JavaScript code will look the same with or without specifying the type of p. You can try it in the TypeScript playground by following this link.

Regardless if a class has a constructor or it doesn’t, classes allow you to declare custom types that didn’t exist in TypeScript before.

NOTE: We use the public access level with each constructor argument in the TypeScript class, which simply means that the generated corresponding properties can be accessed from any code located both inside and outside of the class.

When you declare the properties of a class, you can also mark them as readonly. Such properties can be initialized either at the declaration point or in the class constructor, and their values can’t be changed afterwards. The readonly qualifier is similar to the const keyword, but the latter can’t be used with class properties.

Getting familiar with class inheritance

In real life, every person inherits some features from his or her parents. Similarly, in the TypeScript world, you can create a new class, based on the existing one. For example, you can create a class Person with some properties and then the class Employee that will _inherit_ all the properties of Person and declare some additional ones.

Inheritance is one of the main features of any object-oriented language. TypeScript has the keyword extends to declare that one class is inherited from the other.

The line 7 in the following screenshot shows how to declare an Employee class that extends the class Person and declares an additional property department. In line 11, we create an instance of the class Employee.

This screenshot was taken from the playground at typscriptlang.org after we entered empl. followed by CTRL-Space on line 13. The TypeScript’s static analyzer recognizes that the type Employee is inherited from Person so it suggests the properties defined in both classes Person and Employee.

In our example, the class Employee is a subclass of Person. Accordingly, the class Person is a superclass of Employee. You can also say that the class Person is an ancestor and Employee is a descendant of Person.

NOTE: Under the hood, JavaScript supports prototypal _object-based_ inheritance, where one object can assign another object as its prototype, and this happens during the runtime. During transpiling to JavaScript, the generated code uses the syntax of the prototypal inheritance as seen in the above screenshot on the right.

In addition to properties, a class can include _methods_ – this is how we call functions declared inside the classes. And if a method(s) is declared in a superclass, it will be inherited by the subclass unless the method was declared with the access qualified private which we’ll discuss a bit later.

The next version of the class Person is shown in the screenshot below, and it includes the method sayHello(). As you can see in line 17, TypeScript included this method in its typeahead help.

You may be wondering, “Is there any way to control which properties and methods of a superclass are accessible from the subclass?”
Actually, a more general question would be “Is there any way to control which properties and methods of a class are accessible from other scripts?” The answer is yes – this is what the private, protected, and public keywords are for, and I’ll cover them in the next blog. Stay tuned…

Advertisement

Why program in TypeScript

A little bit of a JavaScript history

In May of 1995, after 10 days of hard work, Brendan Eich wrote the JavaScript programming language. This scripting language didn’t need a compiler and was meant to be used in the web browser Netscape Navigator. No compilers were needed for deploying a program written in JavaScript in the browser. Adding a tag with the JavaScript sources (or a reference to the file with sources) would instruct the browser to load and parse the code and execute it in the browser’s JavaScript engine. People enjoyed the simplicity of the language – no need to declare types of variables, no need to use any tools – just write your code in a plain text editor and use it in a web page.

JavaScript is a dynamic language, which would give additional freedom for software developers. No need to declare properties of an object as the JavaScript engine would create the property during the runtime if the object didn’t already have it.

Actually, there’s no way to declare the type of a variable. The JavaScript engine will guess the type based on the assigned value (e.g. var x = 123 would mean that x is a number). If later on, the script would have an assignment x = 678, the type of x would automatically change from a number to string.

Did you really want to change the type of x or it’s a mistake? You’ll know it only during the runtime as there is no compiler to warn you about it.

JavaScript is a very forgiving language, which is not a shortcoming if the codebase is small and you’re the only person working on this project. Most likely, you remember that x supposed to be a number, and you don’t need any help with this. And of course, you’ll work your current employer forever so the variable x is never forgotten.

Over the years, JavaScript became super popular and de facto standard programming language of the web. But if 20 years ago we’d use JavaScript just to display web pages with some content and make these pages interactive, today we develop complex web apps that contain thousands of lines of code developed by teams of developers. And you know what? Not everyone in your team remembers that x supposed to be a number.

To be more productive, software developers could help from the tooling like IDE with auto-complete features, easy refactoring et al. But how an IDE can help you with refactoring if the language allows complete freedom in adding properties to objects and changing types on the fly?

Everyone realized that replacing JavaScript in all different browsers with another language is not realistic, so new languages were created. They were more tooling-friendly during development, but the program would still have to be converted to JavaScript before deployment so every browser would support them. TypeScript is one of such languages, and let’s see what makes it stand out.

Why program in TypeScript

TypeScript is a compile-to-JavaScript language, which was released by Microsoft as an open source project in 2012. A program written in TypeScript has to be transpiled into JavaScript first, and then it can be executed in the browser or a standalone JavaScript engine.

The difference between transpiling and compiling is that the latter turns the source code of a program into bytecode or machine code, whereas the former converts the program from one language to another, e.g. from TypeScript to JavaScript. But in TypeScript community, the word compile is more popular, and I’ll use it to describe the process of conversion of the TypeScript code into JavaScript.

You may wonder, why go through a hassle of writing a program in TypeScript and then compiling it into JavaScript, if you could write this program in JavaScript in the first place? To answer this question, let’s look at the TypeScript from a very high-level perspective.

TypeScript is a superset of JavaScript, and you can take any JavaScript file, e.g. myProgram.js, change its name extension from .js to .ts, and most likely, the file myProgram.ts becomes a valid TypeScript program. I say most likely, because your JavaScript code may have hidden type-related bugs, you may dynamically change the types of object properties or add new ones after the object was declared and some other things that can be revealed only after your JavaScript code is compiled.
In general, the word superset means that it contains everything that the set has plus something else. The main addition to the “JavaScript set” is that TypeScript also supports static typing whereas JavaScript supports only dynamic typing. Here, the word typing refers to assigning types to program variables.

In programming languages with static typing, a type must be assigned to a variable before you can use it. In TypeScript, you can declare a variable of a certain type, and any attempt to assign to it a value of a different type results in a compilation error. This is not the case in JavaScript, which doesn’t know about the types of your program variables until the runtime. Even in the running program, you can change the type of a variable just by assigning to it a value of different type.

For example, if you declare a variable as a string, trying to assign a numeric value to it will result in the compile-time error.

let customerId: string
customerId = 123; // compile-time error

JavaScript decides on the variable type during the runtime, and the type can be dynamically changed as in the following example:

let customerId = "A15BN"; // OK, customerId is a string
customerId = 123; // OK, from now on it's a number

Now let’s consider a JavaScript function that applies a discount to a price. It has two arguments and both must be numbers.

function getFinalPrice(price, discount) {
   return price - price / discount;
}

How do you know that the arguments must be numbers? First of all, you authored this function some time ago and having an exceptional memory, you may just remember all types of all functions arguments. Secondly, you used descriptive names of the arguments that hint their types. Thirdly, you could guess the types by reading the function code.

This is a pretty simple function, but let’s say someone (not you) would invoke this function by providing a discount as a string, this function would print NaN during runtime.

console.log(getFinalPrice( 100, "10%")); // prints NaN

This is an example of a runtime error caused by the wrong use of a function. In TypeScript, you could provide the types for the function arguments, and such a runtime error would never happen. If someone would try to invoke the function with a wrong type of an argument, this error would be caught as you were typing. Let’s see it in action.

The official TypeScript web page is located at http://www.typescriptlang.org. It offers the language documentation and a playground, where you could enter the code snippets in TypeScript, which would be immediately compiled into JavaScript.

Follow this link, and you’ll see our code snippet in the TypeScript playground, with the squiggly red line under the “10%”. If you hover the mouse over the erroneous code, you’ll see a prompt explaining the error as shown in the screenshot below.

This error is caught by the TypeScript static code analyzer as you type even before you compile this code with tsc. Moreover, if you specify the variable types, your editor or IDE would offer the auto-complete feature suggesting you the argument names and types of the getFinalPrice() function.

Isn’t it nice that errors are caught before runtime? We think so. The vast majority of the developers with the background in such languages as Java, C++, C# take it for granted that the errors are caught during compile time, and this is one of the main reasons why they like TypeScript.

NOTE: There are two types of programming errors – those that are immediately reported by the tools as you type, and those that are reported by the users of your program. Programming in TypeScript substantially decreases the number of the latter.

Still, some of the hard-core JavaScript developers say that TypeScript slows them down by requiring to declare types, and in JavaScript, they’d be more productive. But the majority of the web developers are not JavaScript ninjas and can appreciate a helping hand offered by TypeScript.

There are more than a hundred programming languages that are compiled to JavaScript, but what makes TypeScript stand out is that its creators follow the ECMAScript standards and implement the upcoming JavaScript features a lot faster than Web browsers vendors.

You can find the current proposals of the new ECMAScript features here. A proposal has to go through several stages to be included in the final version of the next ECMAScript spec. If a proposal makes it to Stage 3, most likely it’s included in the latest version of TypeScript.

In the Summer of 2017, the async and await keywords were included into the ECMAScript specification ES2017, a.k.a. ES8. It took more than a year for major browsers to start supporting these keywords. But TypeScript supported them since November of 2015. This means that TypeScript developers could start using these keywords about three years earlier than those who waited for the browsers’ support.

And the best part is that you can use the future JavaScript syntax in today’s TypeScript code and compile it down to the older JavaScript syntax (e.g. ES5) supported by all browsers!

Having said that, we’d like to make a clear distinction between the syntax described in the latest ECMAScript specifications, and the syntax that’s unique to TypeScript. That’s why we recommend you to read the Appendix A first, so you know where ECMAScript ends and TypeScript begins.

Although JavaScript engines do a decent job of guessing the types of variables by their values, development tools have a limited ability to help you without knowing the types. In mid- and large-size applications, this JavaScript shortcoming lowers the productivity of software developers.

The generated JavaScript code is easy to read, and it looks like hand-written code.

TypeScript follows the latest specifications of ECMAScript and adds types, interfaces, decorators, class member variables (fields), generics, enums, the keywords public, protected, and private and more. Check the TypeScript roadmap to see what’s available and what’s coming in the future releases of TypeScript.

Five facts about TypeScript
***************
1. The core developer of TypeScript is Andres Hejlsberg, who also designed Turbo Pascal and Delphi, and is the lead architect of C# at Microsoft.

2. At the end of 2014, Google approached Microsoft asking if they could introduce decorators in TypeScript so this language could be used for developing of the Angular 2 framework. Microsoft agreed, and this gave a tremendous boost to the TypeScript popularity given the fact that hundreds of thousands of developers use Angular.

3. As of September of 2018, the TypeScript compiler had more than three million downloads per week from npmjs.org, and this is not the only TypeScript repository. In April of 2019, it was about 6 million per week. For current statistics, visit this page.

4. As per Redmonk, a respectful software analytics firm, TypeScript came 12th in the programming language rankings chart in January of 2019.

5. According to the StackOverflow Survey 2019, TypeScript is the third (tied for 2nd) most loved language.
***************

And one more thing. Some JavaScript developers are still in denial and say, “If I’ll be programming in TypeScript, I’ll need to introduce an extra step between writing code and seeing it running – the compilation.” When I hear such an argument, I want to ask, “Do you really want to stick to the ES5 version of JavaScript ignoring all the latest syntax introduced by ES6, 7, 8, and 9? If not, then you’ll have the compilation step in your workflow anyway – compile a newer JavaScript into the ES5 syntax.”

To continue getting familiar with TypeScript, read about the structural type system here.

Learning TypeScript: Structural vs nominal typing systems

After completing the second edition of the book “Angular Development with TypeScript“, my colleague Anton Moiseev and I started working on yet another book for Manning. This one will be called “TypeScript Quickly” and its tentative Table of Contents is available here.

This book will cover the main syntax elements of the TypeScript language, and to make the book more interesting, we’ll also develop a blockchain app.
Meanwhile, I’ll start a series of blogs on the TypeScript-related topics. This one is about TypeScript’s structural type system.

A primitive type has just a name (e.g. number) while a more complex type like an object or class has a name and some structure represented by properties (e.g. a class Customer has properties name and address).

How would you know if two types are the same or not? In some languages (e.g. Java) two types are the same if they have the same names, which represents a nominal type system. In Java, the last wouldn’t compile because the names of the classes are not the same even though they have the same structure:

class Person {
	String name;
}

class Customer {
	String name;
}

Customer cust = new Person();  // compiler's error

But TypeScript and some other languages use the structural type system. In the following code snippet I re-wrote the above code snippet in TypeScript:

class Person {
	name: string;
}

class Customer {
	name: string;
}

const cust: Customer = new Person(); // no errors  

This code doesn’t report any errors because TypeScript uses structural type systems, and since both classes Person and Customer have the same structure, it’s OK to assign an instance of one class to a variable of another.

Moreover, you can use object literals to create objects and assign them to class-typed variables or constants as long as the shape of the object literal is the same. The following code snippet will compile without errors:

class Person {
	name: string;
}

class Customer {
	name: string;
}

const cust: Customer = { name: 'Mary' };   
const pers: Person = { name: 'John' };

Our classes didn’t define any methods, but if both of them would define a method(s) that has the same signature (name, arguments, and the return type) they would also be compatible.

What if the structure of Person and Customer are not exactly the same? Let’s add a property age to the class Person as is the following listing:

class Person {
    name: string;
    age: number;    // 1
}

class Customer {
	name: string;
}

const cust: Customer = new Person(); // still no errors  

1 We’ve added this property

Still no errors! TypeScript sees that Person and Customer have the same shape. We want to use the constant of type Customer (it has the property name) to point at the object of type Person (it also has the property name).

Follows the link https://bit.ly/2MbHvpH and you’ll see this code in TypeScript playground (a REPL to try code snippets in TypeScript and compile them into JavaScript). Click Ctrl-Space after the dot in cust. and you’ll see that only the name property is available even though the class Person has also the property age.

Homework: Can the class Customer have more properties than Person?
In the previous code snippet, the class Person had more properties than Customer and the code compiled without errors. What if the class Customer has more properties than Person? Would the following code compile? Explain your answer.

class Person {
    name: string;
}

class Customer {
    name: string;
    age: number;
}

const cust: Customer = new Person();

As they say, “If it walks like a duck and it quacks like a duck, then it must be a duck”. That’s why structural typing is also known as duck typing. If an object can be used for a particular purpose, use it. Yes, it’s not a duck, but at least it walks like a duck, which is all that matters in this context.

Starting a new book on TypeScript

It’s Saturday morning and it’s raining in New York City. There is not much you can do. Why not start writing a new book? The agreement with the publisher is signed, and my colleague Anton Moiseev kindly agreed to be my co-author again. The book will have a title TypeScript Quickly, and its first chapters have to be released in October 2018.

In this blog, I’ll show you the first two pages that I just wrote as well as a table of contents (subject to change). Besides introducing the code samples illustrating the syntax of the language, we’ll be developing a blockchain app using TypeScript in different environments: in Node.js, in the browser without frameworks, with Angular, with React… Meanwhile, the first two pages are ready.

Unit 1. Getting started with TypeScript

This unit starts by presenting the benefits of programming in TypeScript over JavaScript. Then we’ll install the TypeScript compiler and the IDE, and you’ll learn about the process of transforming a TypeScript program into its JavaScript equivalent that can be run in any JavaScript engine. After that, you’ll see how various TypeScript types can be used in a program. In the hands-on section, we’ll introduce you to the blockchain project and will develop a library that will be used in subsequent units.

We’d like to make a clear distinction between the syntax introduced in ECMAScript specification, and the syntax that’s unique to TypeScript. That’s why we recommend you to read the Appendix A first, so you know where ECMAScript ends and TypeScript begins.

Why program in TypeScript

TypeScript is a compile-to-JavaScript language. It’s also a superset JavaScript, which means that you can take any JavaScript file, e.g. myProgram.js, change its name extension from .js to .ts, and the file myProgram.ts becomes a valid TypeScript program without changing a single line of code.

The word superset means that it contains something additional compared to the set. The main addition to the JavaScript is static types. You can declare a variable of a certain type, and any attempt to assign a value of a different type to it results in a compilation error. This is not the case in JavaScript, where you can change the type of a variable anytime you want during runtime.

But web browsers don’t support TypeScript and this won’t change in the foreseeable future. The program written in TypeScript has to be transpiled into JavaScript first, and then it can be executed in the browser or a standalone JavaScript engine.

The difference between transpiling and compiling is that the latter turns the source code of a program into a bytecode or machine code, whereas the former converts the program from one language to another, e.g. from TypeScript to JavaScript.

Then why go through a hassle of writing a program in TypeScript and then transpiling it into JavaScript, if you could write this program in JavaScript in the first place?

In essence, TypeScript is JavaScript with static types. For example, if you declare a variable as a string, trying to assign a numeric value to it will result in the compile-time error.

let customerId: string
customerId = 123;  // compile-time error

In JavaSript, you can’t explicitly assign the type to a variable, and you could write

let customerId = "A15BN";
customerId = 123;  // no errors 

Let’s write a JavaScript function that applies the provided discount to a price. It has two arguments and both must be numbers.

function getFinalPrice(price, discount) {
  return price - price/discount;
}

How do you know that the arguments must be numbers? First of all, you wrote this function and having an exceptional memory, you may just remember all types of all functions arguments. Secondly, you use descriptive names of the arguments that hint their types. Thirdly, you could guess the types by reading the function code.

This is a pretty simple function, which is not always the case. But let’s say someone (not you) would invoke this function by providing a discount as a string, this function would print NaN during the runtime.

console.log(getFinalPrice( 100, 10));    // prints 90
console.log(getFinalPrice( 100, "10%")); // prints NaN

In TypeScript, you could provide the types for the function arguments, so if someone would try to invoke the function with a wrong type of an argument, this error would be caught as you were typing. Let’s see it in action.

The official TypeScript web page is located here. It offers the language documentation and a playground, where you could enter the code snippets in TypeScript, which would be immediately transpiled into JavaScript.

Follow this link https://bit.ly/2IyVNlj, and you’ll see our code snippet in the TypeScript playground, with the squiggly red line under “10%”. If you hover the mouse over the erroneous code, you’ll see a prompt explaining the error as shown below.

This error was caught by the TypeScript static code analyzer as I was typing. Moreover, if you specify the variable types, your IDE would offer the auto-complete feature suggesting you the argument names and types of the getFinalPrice() function.

Isn’t it nice that the errors are caught during the compile time? I think so. The vast majority of the developers with the background in such languages as Java, C++, C# and others take it for granted that the errors are caught during compile time, and they welcome TypeScript.

Having said that, I need to admit that some of the hard-core JavaScript developers say that TypeScript slows them down by requiring to use types, and in JavaScript, they’d be more productive. But the majority of the web developers are not JavaScript ninjas and can appreciate a helping hand offered by TypeScript.

This is all I got so far.

Below is the current version of the Table of Contents.

Unit 1: Getting started with TypeScript
1.1 Why developing in TypeScript
1.2 Installing and using the TypeScript compiler
1.3 Introducing the Visual Studio Code IDE
1.4 Getting familiar with TypeScript syntax
1.4.1 Type annotations and inferred types
1.5. Hands-on: Starting the blockchain project
1.5.1 Introducing the blockchain project
1.5.2 Developing a library that implements a mining algorithm

Unit 2 Classes and interfaces
2.1 Classes
2.1.1 Instance and static methods
2.1.2 Properties and access modifiers public, private, protected
2.1.3 Constructors
2.1.4 Abstract classes
2.2 Interfaces
2.2.1 Declaring custom types with interfaces
2.2.2 Interface as a contract
2.2.3 Declaring types with classes vs interfaces
2.3 Hands-on: Developing a browser-based blockchain node with TypeScript
2.3.1 Working with DOM elements
2.3.2 Making AJAX requests
2.3.3 Implementing the blockchain node for

Unit 3 Generics
3.1 Intro to Generics
3.2 Creating custom generics
3.3 Hands-on: Developing Angular client for the browser-based blockchain node
3.3.1 Brief overview of Angular
3.3.2 Creating a new app with Angular CLI
3.3.3 Generating Angular components and services
3.3.4 Implementing the blockchain node in Angular

Unit 4 Tooling
4.1 Improving code quality with TSLint
4.2 Bundling the TypeScript code with Webpack
4.4 Debugging TypeScript in the browser
4.5 Unit testing TypeScript code
4.7 Hands-on: Developing React client for the browser-based blockchain node
4.7.1 Brief overview of React
4.7.2 Transpiling TypeScript with Babel
4.7.3 Creating a React app for the blockchain node

Unit 5 Advanced types
5.1 Unions, intersections, and the type keyword
5.2 Enums
5.3 Mapped types
5.4 Conditional types
5.5. Hands-on: Developing a server for discovering blockchain nodes in the network

Unit 6 Advanced TypeScript features
6.1 Decorators
6.1.1 Creating custom decorators
6.2 Mixins
6.3 Dynamic imports
6.4 Hands-on: Implementing peer-to-peer blockchain nodes communication
6.4.1 Introducing WebRTC
6.4.2 Implementing nodes communication via WebRTC

Appendix A Modern JavaScript
A.1 The keywords let and const
A.2 Functions
A.2.1 Default and optional function parameters
A.2.2 Fat arrow function expressions
A.3 Classes and inheritance
A.4. Asynchronous programming
A.4.1 From callbacks to promises
A.4.2 async and await
A.5 Destructuring
A.6 The Spread operator
A.6.1 Cloning objects with the Spread operator
A.7 The Rest operator
A.8 Iterating data collections

Appendix B Using TypeScript with JavaScript libraries
B.1 Type declaration files
B.1.1 How to create type declaration files
B.2 Using the JavaScript lodash library in TypeScript code

RxJS Essentials. Part 5: The flatMap operator

In this article I’ll introduce an RxJS flatMap() operator. Previous articles in this series include:

1. Basic Terms
2. Operators map, filter, and reduce
3. Using Observable.create()
4. Using RxJS Subject

In some cases, you need to treat each item emitted by an observable as another observable. In other words, the outer observable emits the inner observables. Does it mean that we need to write nested subscribe() calls (one for the outer observable and another for the inner one)? No, we don’t. The flatMap() operator takes each item from the outer observable and auto-subscribes to it.

Some operators are not explained well in RxJS documentation, and we recommend you to refer to the general ReaciveX (reactive extensions) documentation for clarification. The flatMap() operator is better explained there, and it states that flatMap() is used to “transform the items emitted by an observable into observables, then flatten the emissions from those into a single observable”. This documentation includes the following marble diagram:

As you see, the flatMap() operator takes an emitted item from the outer observable (the circle) and unwraps its content (the inner observable of diamonds) into the flattened output observable stream. The flatMap() operator merges the emissions of the inner observables so their items may interleave.

The following code listing has an observable that emits drinks, but this time it emits not individual drinks, but palettes. The first palette has beers and the second – soft drinks. Each palette is observable. We want to turn these two palettes into an output observable with individual beverages.

function getDrinks() {

    let beers = Rx.Observable.from([   // 1
        {name: "Stella", country: "Belgium", price: 9.50},
        {name: "Sam Adams", country: "USA", price: 8.50},
        {name: "Bud Light", country: "USA", price: 6.50}
    ], Rx.Scheduler.async);

    let softDrinks = Rx.Observable.from([    // 2
        {name: "Coca Cola", country: "USA", price: 1.50},
        {name: "Fanta", country: "USA", price: 1.50},
        {name: "Lemonade", country: "France", price: 2.50}
    ], Rx.Scheduler.async);

    return Rx.Observable.create( observer => {
            observer.next(beers);     // 3
            observer.next(softDrinks);   // 4
            observer.complete();
        }
    );
}

// We want to "unload" each palette and print each drink info

getDrinks()
  .flatMap(drinks => drinks)    // 5   
  .subscribe(  // 6
      drink => console.log("Subscriber got " + drink.name + ": " + drink.price ),
      error => console.err(error),
      () => console.log("The stream of drinks is over")
  );

1. Creating an async observable from beers
2. Creating an async observable from soft drinks
3. Emitting the beers observable with next()
4. Emitting the soft drinks observable with next()
5. Unloading drinks from pallets into a merged observable
6. Subscribing to the merged observable

This script will produce the output that may look as follows (note that the drinks interleave):

Subscriber got Stella: 9.5
Subscriber got Coca Cola: 1.5
Subscriber got Sam Adams: 8.5
Subscriber got Fanta: 1.5
Subscriber got Bud Light: 6.5
Subscriber got Lemonade: 2.5
The stream of observables is over

To see it in CodePen visit this link.

Are there any other uses of the flatMap() operator besides unloading palettes of drinks? Another scenario where you’d want to use flatMap() is when you need to execute more than one HTTP request, where the result of the first request should be given to the second one. In Angular, HTTP requests return observables and without flatMap() this could be done (it a bad style) with nested subscribe() calls:

this.httpClient.get('/customers/123')
  .subscribe(customer => {
              this.httpClient.get(customer.orderUrl)
              .subscribe(response => this.order = response)
  })

The method httpClient.get() returns an observable, and the better way to write the above code is by using the flatMap() operator, which auto-subscribes and unwraps the content of the first observable and makes another HTTP request:

httpClient.get('./customers/123')
          .flatMap(customer => this.httpClient.get(customer.orderURL))
          .subscribe(response => this.order = response);

Since a flatMap() is a special case of map(), you can specify a transforming function while flattening the observables into a common stream. In the above example, we transform the value customer into a function call httpClient.get().

TIP: In RxJS, flatMap() is an alias of mergeMap() so these two operators have the same functionality.

Let’s consider one more example of using flatMap(). This example will be a modified version of the traders-orders example used in the article “Using RxJS Subject“. This example is written in TypeScript and it uses two Subject instances:

* traders – this Subject keeps track of traders
* orders – this Subject is declared inside the class Trader and keeps track of each order placed by a particular trader.

You’re the manager who wants to monitor all orders placed by all traders. Without flatMap(), you’d need to subscribe to traders (the outer observable) and create a nested subscription for orders (the inner observable) that each subject has. Using flatMap() allows you to write just one subscribe() call, which will be receiving the inner observables from each trader in one stream.

import {Subject} from 'rxjs/Subject';
import 'rxjs/add/operator/mergeMap';

enum Action{
    Buy = 'BUY',
    Sell = 'SELL'
}

class Order{
    constructor(public orderId: number, public traderId: number, public stock: string, public shares: number, public action:Action){}
}

let traders = new Subject<Trader>();  // 1

class Trader {

    orders = new Subject<Order>();   // 2

    constructor(private traderId:number, public traderName:string){}
}

let tradersSubscriber = traders.subscribe(trader => console.log(`Trader ${trader.traderName} arrived`))

let ordersSubscriber = traders        // 3
  .flatMap(trader => trader.orders)   // 4
  .subscribe(ord =>      // 5
       console.log(`Got order from trader ${ord.traderId} to ${ord.action} ${ord.shares} shares of ${ord.stock}`));

let firstTrader = new Trader(1, 'Joe');
let secondTrader = new Trader(2, 'Mary');

traders.next(firstTrader);
traders.next(secondTrader);

let order1 = new Order(1, 1,'IBM',100,Action.Buy);
let order2 = new Order(2, 1,'AAPL',200,Action.Sell);
let order3 = new Order(3, 2,'MSFT',500,Action.Buy);

// Traders place orders
firstTrader.orders.next( order1);
firstTrader.orders.next( order2);
secondTrader.orders.next( order3);

1. Declare the Subject for traders
2. Each trader has its own Subject for orders
3. Starting with the outer observable traders
4. Extracting the inner observable from each Trader instance
5. The function subscribe() receives a stream of orders

In this version of the program, the class Trader doesn’t have a method placeOrder(). We just have the trader’s observable orders push the order to its observer by using the method next(). Remember, a Subject has both observable and observer.

The output of this program is shown next.

Trader Joe arrived
Trader Mary arrived
Got order from trader 1 to BUY 100 shares of IBM
Got order from trader 1 to SELL 200 shares of AAPL
Got order from trader 2 to BUY 500 shares of MSFT

In our example, the subscriber just prints the orders on the console, but in a real world app it could invoke another function that would be placing orders with the stock exchange for execution.

To see it in CodePen, follow this link. In the next article you’ll learn about a very useful operator switchMap().

If you have an account at O’Reilly’s safaribooksonline.com, you can watch my video course “RxJS Essentials” there.

TypeScript Generics

TypeScript supports parameterized types, also known as generics, which can be used in a variety of scenarios. For example, you can create a function that can take values of any type, but during its invocation, in a particular context, you can explicitly specify a concrete type.

Take another example: an array can hold objects of any type, but you can specify which particular object types (for example, instances of Person) are allowed in an array. If you were to try to add an object of a different type, the TypeScript compiler would generate an error.

Generics syntax

The following code snippet declares a Person class, creates two instances of it, and stores them in the workers array declared with the generic type. Generic types are denoted by placing them in the angle brackets (for example, ).

class Person {
    name: string;
}

class Employee extends Person{
    department: number;
}

class Animal {
    breed: string;
}

let workers: Array<Person> = [];

workers[0] = new Person();
workers[1] = new Employee();
workers[2] = new Animal();  // compile-time error

Here we declare the Person, Employee, and Animal classes and a workers array with the generic type. By doing this, we announce our plans to store only instances of the class Person or its descendants. An attempt to store an instance of an Animal in the same array will result in a compile-time error.

Nominal and Structural type systems

After using generics in Java for 10 years, I quickly noticed that the syntax is the same and was about to check off this syntax element as “got it”. But it was a little too soon. While Java, C++, or C# use nomimal type system, TypeScript uses the structural one. In the nominal system, types are checked against their names, but in a structural system by their structure.

With the nominal type system the following line would result in an error:

let person: Person = new Animal();

With a structural type system, as long as the structures of the type are similar, you may get away with assigning an object of one type to a variable of another. Let’s illustrate it by adding the property name to the class Animal as seen on the screenshot below.

Now the TypeScript compiler doesn’t complain about assigning an Animal object to the variable of type Person. The variable of type Person expects an object that has a property name, and the Animal object has it. This is not to say that Person and Animal represent the same types, but these types a compatible. Trying to assign the Person object to a variable of type Animal will result in the compilation error “Property breed is missing in type Person”:

let worker: Animal = new Person(); // compilation error

Can you use generic types with any object or a function? No. The creator of the object or function has to allow this feature. If you open TypeScript’s type definition file (lib.d.ts) on GitHub and search for “interface Array,” you’ll see the declaration of the Array, as shown below.

The <T> in line 1008 means TypeScript allows you to declare a type parameter with Array and the compiler will check for the specific type provided in your program. The next code listing specifies this generic <T> parameter as <Person>. But because generics aren’t supported in JavaScript, you won’t see them in the code generated by the transpiler. It’s just an additional safety net for developers at compile time.

You can see another T in line 1022 in figure B.7. When generic types are specified with function arguments, no angle brackets are needed. But there’s no actual T type in TypeScript. The T here means the push method lets you push objects of a specific type into an array, as in the following example:

workers.push(new Person());

Creating your own parameterized types

You can create your own classes or functions that support generics as well. In the next listing, we defined an interface Comparator that declares a method compareTo() expecting the concrete type to be provided during this method invocation.

interface Comparator {                   // 1
    compareTo(value: T): number;
}

class Rectangle implements Comparator {    // 2

    constructor(private width: number, private height: number){};

    compareTo(value: Rectangle): number{   // 3
        if (this.width*this.height &gt;= value.width*value.height){
            return 1;}
        else  {
            return -1;
        }
    }
}

let rect1:Rectangle = new Rectangle(2,5);  
let rect2: Rectangle = new Rectangle(2,3);

rect1.compareTo(rect2)===1? console.log("rect1 is bigger"): 
                            console.log("rect1 is smaller") ;   // 4


class Programmer implements Comparator {    // 5

    constructor(public name: string, private salary: number){};

    compareTo(value: Programmer): number{  // 6
        if (this.salary &gt;= value.salary){
            return 1;}
        else  {
            return -1;
        }
    }
}

let prog1:Programmer = new Programmer("John",20000);
let prog2: Programmer = new Programmer("Alex",30000);

prog1.compareTo(prog2)===1? console.log(${prog1.name} is richer):
                           console.log(${prog1.name} is poorer) ;  // 7

1. Declare an interface Comparator with a generic type

2. Create a class that implements Comparator specifying the concrete type Rectangle

3. Implement the method for comparing rectangles

4.Compare rectangles (the type T is erased and replaced with Rectangle)

5. Create a class that implement Comparator specifying the concrete type Programmer

6.Implement the method for comparing programmers

7. Compare programmers (the type T is erased and replaced with Programmer)

Even though generics are erased during the JavaScript code generation, use them to minimize the number of runtime errors. When you use libraries or frameworks written in TypeScript, you have no choice but use generics to use the API provided by these libraries.

If you live in New York, stop by at the Java SIG meetup on August 23, 2017 where I’ll be delivering a presentation “TypeScript for Java Developers”.

TypeScript generics and animal workers

I’ve been using Java generics for years, and when I saw their syntax in TypeScript, I simply put a checkmark in the list of TypeScript features that I already know and understand.I was wrong. Let me show you something.

Below is a Java code sample that illustrates the use of generics. I’ve created a class Person and its subclass Employee. Then I created a standalone class Animal. Finally, I used the generic notation to ensure that if anyone would try to add an instance of Animal to the collection of workers, the Java compiler would complain, and it did:

Then I re-wrote the same program in TypeScript, and its compiler didn’t complain:

But if I’ll comment out the property name in the class Animal, the TypeScript compiler will complain:

This may lead to the following conclusions:

1. In TypeScript, if you use a type as a parameter in generics, it’ll allow any other type as long as it has the same properties (e.g. Person.name and Animal.name)
2. In TypeScript, animals can be workers

If there is something in TypeScript documentation that has different explanations to this behavior, please let me know. Generics is an interesting subject and I’ll write another blog soon.

TypeScript: callable interfaces

TypeScript is a superset of JavaScript and over the last year it’s gaining popularity by leaps and bounds. Angular 2 and RxJS 5 are written in Typescript. I believe about a million of developers are using TypeScript today for app development (this is not official stats). I’m using TypeScript for more than a year and it’s so much more productive than JavaScript! For me (a Java developer), TypeScript makes a lot more sense than JavaScript. But if your main language was JavaScript, some of the TypeScript’s concepts might look foreign for you. I’m planning to write a couple of blogs illustrating TypeScript syntax.

Web browsers don’t understand TypeScript and there’re no plans to change this any time soon. So if you’ll write a program in TypeScript, it has to by transpiled (think compiled) into JavaScript first. I’m not going to discuss the TypeScript compiler here, but will be using the Playground, where you can write code fragments in TypeScript, and they’ll be immediately transpiled into JavaScript (it’s going to be the ECMAScript 5 version).

TypeScript supports different flavors of interfaces. Today we’ll get familiar with a callable interface that contains a bare function signature (a signature without a function name). I’ll show you the syntax first and then will explain how a callable interfaces are useful. The following example shows a bare function signature that takes one parameter of type number and returns a boolean.

(percent: number): boolean;

The bare function signature indicates that when this function will be implemented it’s going to be callable. So what’s the big deal? Let’s consider an example that declares IPayable interface, which will contain a bare function signature. In our company work employees and contractors that will be represented by a class Person. The rules for increasing pay of employees and contractors are different, and I’ll create separate functions that implement these rules. These functions will be passed as arguments to the constructor of the class Person and will be invoked inside the constructor of the Person instances.

interface IPayable { // <1>
    (percent: number): boolean;
}

class Person  {
    constructor(private validator: IPayable) { // <2>
    }

    increasePay(percent: number): boolean { // <3>
        return this.validator(percent);
    }
}

let forEmployees: IPayable = (percent) => { // <4>
        console.log("Increasing salary by ", percent);
        return true;
    };

let forContractors: IPayable = (percent) => { // <5>
    var increaseCap: number = 20;

    if (percent < increaseCap) {
      console.log("Increasing hourly rate by", percent);
      return true;
    } else {
      console.log("Sorry, the increase cap for contractors is ",
                                         increaseCap);
      return false;
    }
}

let workers: Array<Person> = [];

workers[0] = new Person(forEmployees); // <6>
workers[1] = new Person(forContractors);

workers.forEach(worker =>worker.increasePay(30)); // <7>

1. A callable interface that include a bare function signature.

2. We declare that the constructor of the Person class takes an implementation of the callable interface IPayable as an argument.

3. The increasePay() method invokes the bare function on the passed implementation of IPayable, supplying the pay increase value for validation.

4. The rules for salary increases for employees are implemented using the arrow function expression.

5. The rules for pay increases for contractors are implemented using the arrow function expression.

6. Instantiates two Person objects, passing different rules for pay increases.

7. Invokes increasePay() on each instance, validating the 30% pay increase.

First I’ll enter the above code in the TypeScript playground on the left, and the generated JavaScript code will be shown on the right (see http://bit.ly/2hUdsGn). Read the JavaScript code – it should help you understanding what’s going on. Note, that there are no traces of our IPayable interface on the right since JavaScript doesn’t support interfaces.

play

If you click on the button Run and open the browser’s console you’ll see the following output:

Increasing salary by 30
Sorry, the increase cap for contractors is 20

Cool. But in JavaScript you can also pass a function as an argument to a higher order function (constructor in our case), right?

Now imagine that you’re supposed to pass a function with a certain signature to a higher order function, but made a mistake and passed a wrong function. This will result in a runtime error.

Callable interfaces allow you to to catch this mistake during the development stage. For that we declare the signature of a function that has to be passed to the constructor of the instance of the Person object.

Now purposely introduce an error – declare a function with the wrong signature (do it on the left side at the playground):

let forTempWorkers = () => 
      console.log("Can't increase salary for temps"); 

Try to pass it to the constructor to a Person:

workers[0] = new Person(forTempWorkers); 

TypeScript will immediately highlight the above line as erroneous, and you’ll catch this error during dev time whereas in JavaScript this error would silently sneak into your code causing the app to blow up during the runtime.

play2

So callable interfaces are your friends, aren’t they?

My videos on Angular framework

Our company, Farata Systems, offers Angular consulting and training. Send an email to training @ faratasystems.com if interested.

Video presentations and workshops