About this book

This book is an insightful journey through the most valuable design patterns, and it will provide clear guidance on how to use them effectively in Angular. You will explore some of the best ways to work with Angular and how to use it to meet the stability and performance required in today's web development world. You’ll get to know some Angular best practices to improve your productivity and the code base of your application.

We will take you on a journey through Angular designs for the real world, using a combination of case studies, design patterns to follow, and anti-patterns to avoid.

By the end of the book, you will understand the various features of Angular, and will be able to apply well-known, industry-proven design patterns in your work.

Publication date:
July 2018


TypeScript Best Practices

I've always hated JavaScript. I use it, sure, but only when necessary. I distinctly remember my first internship interview, back when I was a freshman at eXia.Cesi, a French computer engineering school. I only knew C and some Java, and I was asked to help on an intranet that mostly worked with homemade Ajax libraries. It was pure madness and kind of steered me away from the web aspect of computer engineering for a while. I find nothing likeable in the following:

var r = new XMLHttpRequest();  
r.open("POST", "webservice", true); 
r.onreadystatechange = function () { 
   if (r.readyState != 4 || r.status != 200) return;  

A native Ajax call. How ugly is that?

Of course, with jQuery modules and some separation of concerns, it can be usable, but still not as comfortable as I would like. You can see in the following screenshot that the concerns are separated, but it's not so easy:

A deprecated toolwatch.io version using PHP5 and Codeigniter

Then, I learned some RoR (a Ruby-based, object-oriented framework for web applications: http://rubyonrails.org/) and Hack (a typed PHP by Facebook: http://hacklang.org/). It was wonderful; I had everything I always wanted: type safety, tooling, and performance. The first one, type safety, is pretty self-explanatory:

class MyClass { 
  public function alpha(): int { 
    return 1; 
  public function beta(): string { 
    return 'hi test'; 
function f(MyClass $my_inst): string { 
  // Fix me! 
  return $my_inst->alpha(); 

Also, with types, you can have great toolings, such as powerful auto completion and suggestions:

Sublime Text autocompletion on toolwatch.io mobile app (Ionic2 [5] + Angular 2 )

Angular can be used with CoffeeScript, TypeScript, and JavaScript. In this book, we'll focus on TypeScript, which is the language recommended by Google. TypeScript is a typed superset of JavaScript; this means that, with TypeScript, you can do everything you used to do in JavaScript, and more! To name but a few advantages: user-defined types, inheritance, interfaces, and visibility. And the best part is that TypeScript is transpiled into JavaScript so that any modern browser can run it.

In fact, with the use of polyfill, even our good old IE6 can almost execute the final output. We'll get back to that in the next chapter. The transpilation is different from compilation (for example, from C to executable or .java to .class) as it only translates TypeScript into JavaScript.

In this chapter, we will learn the best practices for TypeScript. The syntax of the TypeScript language is quite easy to grasp for anyone who knows JavaScript and an object-oriented language. If you don't know anything about object-oriented programming, I'd suggest you put this book aside for a few moments and take a look at this quick Udacity course: https://www.udacity.com/wiki/classes.

As a summary of the topics covered:

  • TypeScript syntax
  • TypeScript best practices
  • TypeScript shortcomings

Environment setup

For the environment setup, I will cover all three major platforms: Debian-flavored Linux, macOS, and Windows. All the tools we are going to use are cross-platform. Consequently, feel free to choose the one you like the most; there is not a thing you will not be able to do later on.

In what follows, we will install Node.js, npm, and TypeScript.

Node.js and npm for Linux

$ curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -
$ sudo apt-get install -y Node.js

This command downloads a script, directly into your bash, that will fetch every resource you need and install it. For most cases, it will work just fine and install Node.js + npm.

Now, this script has one flaw; it will fail if you have Debian repositories that are no longer available. You can either take this opportunity to clean your Debian repositories or edit the script a bit.

$ curl https://deb.nodesource.com/setup_6.x > node.sh 
$ sudo chmod +x node.sh 
$ vim node.sh 
//Comment out all apt-get update 
//Save the file 
$ sudo apt-get update 
$ ./node.sh 
$ sudo apt-get update 
$ sudo apt-get install -y Node.js 

Then, go to https://Node.js.org/en/download/, and download and install the last .pkg or .msi (for Linux or Windows, respectively).


Now, you should have access to node and npm in your Terminal. You can test them out with the following commands:

$ node -v 
$ npm -v 

Note that the output of these commands (for example, v6.2.1 and 3.9.3) can be different, and your environment as the latest version of node and npm can, and most certainly, will be different by the time you read these lines. However, if you at least have these versions, you will be fine for the rest of this book:

    $ npm install -g TypeScript

The -g argument stands for global. In the Linux system, depending on your distribution, you might need sudo rights to install global packages.

Very much like node and npm, we can test whether the installation went well with the following:

    $ tsc -v
    Version 2.6.1

What we have, for now, is the TypeScript transpiler. You can use it like so:

    tsc --out myTranspiledFile.js myTypeScriptFile.ts

This command will transpile the content of myTypeScriptFile.ts and create myTranspiledFile.js. Then, you can execute the resultant js file, in the console, using node:

    node myTranspiledFile.js

To speed up our development process, we will install ts-node. This node package will transpile TypeScript files into JavaScript and resolve the dependencies between said files:

    $ npm install -g ts-node
    $ ts-node -v

Create a file named hello.ts and add the following to it:

console.log('Hello World'); 

Now, we can use our new package:

    $ ts-node hello.ts 
    Hello World

Quick overview

In this section, I'll present a quick overview of TypeScript. This presentation is by no means exhaustive, as I will explain particular concepts when we come across them. However, here are some basics.

TypeScript is, as I've mentioned, a typed superset of JavaScript. While TypeScript is typed, it only proposes four base types for you to use out of the box. The four types are String, number, Boolean, and any. These types can, using the : operator, type var name: string variables or function arguments and return the add(a:number, b:number):number type function. Also, void can be used for functions to specify that they don't return anything. On the object-oriented side, string, number, and boolean specialize any. Any can be used for anything. It's the TypeScript equivalent of the Java object.

If you need more than these types, well, you'll have to create them yourself! Thankfully, this is pretty straightforward. Here's the declaration of a user class that contains one property:

class Person{

You can create a new Person instance with the simple command shown here:

var p:Person = new Person();
p.name = "Mathieu"

Here, I create a p variable that statically (for example, the left-hand side) and dynamically (for example, the right-hand side) stands for a Person. Then, I add Mathieu to the name property. Properties are, by default, public, but you can use the public, private, and protected keywords to refine their visibility. They'll behave as you'd expect in any object-oriented programming language.

TypeScript supports interfaces, inheritance, and polymorphism in a very simple fashion. Here is a simple hierarchy composed of two classes and one interface. The interface, People, defines the string that will be inherited by any People implementation. Then, Employee implements People and adds two properties: manager and title. Finally, the Manager class defines an Employee array, as shown in the following code block:

interface People{ 
class Employee implements People{ 
class Manager extends Employee{ 

Functions can be overridden by functions that have the same signature, and the super keyword can be used to refer to the parent implementation, as shown in the following snippet:

Interface People { 
   name: string; 
class Employee implements People { 
   name: string; 
   manager: Manager; 
   title: string; 
               "I am", this.name,  
               ". My job is title and my boss is",  
class Manager extends Employee { 
   team: Employee[]; 
   presentSelf(): void { 
         console.log("I also manage", this.team.toString()); 

The last thing you need to know about TypeScript before we move on to the best practices is the difference between let and var. In TypeScript, you can use both to declare a variable.

Now, the particularity of variables in TypeScript is that it lets you decide between a function and a block scope for variables using the var and let keywords. Var will give your variable a function scope, while let will produce a block-scoped variable. A function scope means that the variables are visible and accessible to and from the whole function. Most programming languages have block scope for variables (such as C#, Java, and C++). Some languages also offer the same possibility as TypeScript, such as Swift 2. More concretely, the output of the following snippet will be 456:

var foo = 123; 
if (true) { 
    var foo = 456; 
console.log(foo); // 456

In opposition, if you use let, the output will be 123 because the second foo variable only exists in the if block:

let foo = 123; 
if (true) { 
    let foo = 456; 
console.log(foo); // 123 

Best practices

In this section, we present the best practices for TypeScript in terms of coding conventions, tricks to use, and features and pitfalls to avoid.


The naming conventions preconized by the Angular and definitely typed teams are very simple:

  • Class: CamelCase.
  • Interface: CamelCase. Also, you should try to refrain from preceding your interface name with a capital I.
  • Variables: lowerCamelCase. Private variables can be preceded by a _.
  • Functions: lowerCamelCase. Also, if a method does not return anything, you should specify that said method returns void for better readability.

Interface redefinitions

TypeScript allows programmers to redefine interfaces, using the same name multiple times. Then, any implementation of said interface inherits all the definitions of all the interfaces. The official reason for this is to allow users to enhance the JavaScript interface without having to change the types of their object throughout their code. While I understand the intent of such a feature, I foresee way too much hassle in its use. Let's have a look at an example feature on the Microsoft website:

interface ICustomerMerge 
   MiddleName: string; 
interface ICustomerMerge 
   Id: number; 
class CustomerMerge implements ICustomerMerge 
   id: number; 
   MiddleName: string; 

Leaving aside the fact that the naming conventions are not respected, we got two different definitions of the ICustomerMerge interface. The first one defines a string and the second one a number. Automatically, CustomerMerge has these members. Now, imagine you have ten-twelves file dependencies, you implement an interface, and you don't understand why you have to implement such and such functions. Well, someone, somewhere, decided it was pertinent to redefine an interface and broke all your code, at once.

Getters and setters

In TypeScript, you can specify optional arguments with the ? operator. While this feature is good and I will use it without moderation in the coming chapters, it opens the door to the following ugliness:

class User{ 
   private name:string; 
   public  getSetName(name?:string):any{ 
         if(name !== undefined){ 
               this.name = name; 
               return this.name 

Here, we test whether the optional name argument was passed with !== undefined. If the getSetName function received something, it'll act as a setter, otherwise, as a getter. The fact that the function doesn't return anything when used as a setter is authorized by any return type.

For clarity and readability, stick to the ActionScript-inspired getter and setter:

class User{
private name:_string = "Mathieu";
get name():String{
return this._name;
set name(name:String){
this._name = name;

Then, you can use them as follows:

var user:User = new User():
if(user.name === "Mathieu") { //getter
user.name = "Paul" //setter


TypeScript constructors offer a pretty unusual, but time-saving, feature. Indeed, they allow us to declare a class member directly. So, instead of this lengthy code:

class User{ 
   constructor(id: number,email: string,name: string, 
         lastname: string,country: string,registerDate:  
         string,key: string){ 
         this.id = id; 
         this.email = email; 
         this.name = name; 
         this.lastname = lastname; 
         this.country = country; 
         this.registerDate = registerDate; 
         this.key = key; 

You could have:

class User{ 
   constructor(private id: number,private email: string,private name: string, 
         private lastname: string,private country: string, private            registerDate: string,private key: string){} 

The preceding code achieves the same thing and will be transpiled to the same JavaScript. The only difference is that it saves you time in a way that doesn't degrade the clarity or readability of your code.

Type guards

Type guards, in TypeScript, define a list of types for a given value. If one of your variables can be assigned to one and only value or a specific set of values, then consider using the type guard over the enumerator. It'll achieve the same functionality while being much more concise. Here's a made-up example with a People person who has a gender attribute that can only be MALE or FEMALE:

class People{
gender: "male" | "female";

Now, consider the following:

class People{
enum Gender{


In opposition to type guards, if your class has a variable that can take multiple values at the same time from a finite list of values, then consider using the bit-based enumerator. Here's an excellent example from https://basarat.gitbooks.io/:

class Animal{ 
   flags:AnimalFlags = AnimalFlags.None 
enum AnimalFlags { 
    None           = 0, 
    HasClaws       = 1 << 0, 
    CanFly         = 1 << 1, 
function printAnimalAbilities(animal) { 
    var animalFlags = animal.flags; 
    if (animalFlags & AnimalFlags.HasClaws) { 
        console.log('animal has claws'); 
    if (animalFlags & AnimalFlags.CanFly) { 
        console.log('animal can fly'); 
    if (animalFlags == AnimalFlags.None) { 
var animal = { flags: AnimalFlags.None }; 
printAnimalAbilities(animal); // nothing 
animal.flags |= AnimalFlags.HasClaws; 
printAnimalAbilities(animal); // animal has claws 
animal.flags &= ~AnimalFlags.HasClaws; 
printAnimalAbilities(animal); // nothing 
animal.flags |= AnimalFlags.HasClaws | AnimalFlags.CanFly; 
printAnimalAbilities(animal); // animal has claws, animal can fly 

We defined the different values using the << shift operator in AnimalFlags, then used |= to combine flags, &= and ~ to remove flags, and | to combine flags.


In this section, we will go over two TypeScript pitfalls that became a problem for me when I was coding Angular 2 applications.

Type-casting and JSON

If you plan to build more than a playground with Angular 2, and you obviously do since you are interested in patterns for performances, stability, and operations, you will most likely consume an API to feed your application. Chances are, this API will communicate with you using JSON.

Let's assume that we have a User class with two private variables: lastName:string and firstName:string. In addition, this simple class proposes the hello method, which prints Hi I am, this.firstName, this.lastName:

class User{
constructor(private lastName:string, private firstName:string){

console.log("Hi I am", this.firstName, this.lastName);

Now, consider that we receive users through a JSON API. Most likely, it'll look something like [{"lastName":"Nayrolles","firstName":"Mathieu"}...]. With the following snippet, we can create a User:

let userFromJSONAPI: User = JSON.parse('[{"lastName":"Nayrolles","firstName":"Mathieu"}]')[0];

So far, the TypeScript compiler doesn't complain, and it executes smoothly. It works because the parse method returns any (that is, the TypeScript equivalent of the Java object). Sure enough, we can convert any into User. However, the following userFromJSONAPI.hello(); will yield:

    TypeError: userFromUJSONAPI.hello is not a function
        at Object.<anonymous> (json.ts:19:18)
        at Module._compile (module.js:541:32)
        at Object.loader (/usr/lib/node_modules/ts-node/src/ts-node.ts:225:14)
        at Module.load (module.js:458:32)
        at tryModuleLoad (module.js:417:12)
        at Function.Module._load (module.js:409:3)
        at Function.Module.runMain (module.js:575:10)
        at Object.<anonymous> (/usr/lib/node_modules/ts-node/src/bin/ts-node.ts:110:12)
        at Module._compile (module.js:541:32)
        at Object.Module._extensions..js (module.js:550:10)

Why? Well, the left-hand side of the assignation is defined as User, sure, but it'll be erased when we transpile it to JavaScript. The type-safe TypeScript way to do it is:

let validUser = JSON.parse('[{"lastName":"Nayrolles","firstName":"Mathieu"}]') 
.map((json: any):User => { 
return new User(json.lastName, json.firstName); 

Interestingly enough, the typeof function won't help you either. In both cases, it'll display Object instead of User, as the very concept of User doesn't exist in JavaScript.

This type of fetch/map/new can rapidly become tedious as the parameter list grows. You can use the factory pattern which we'll see in Chapter 3, Classical Patterns, or create an instance loader, such as:

class InstanceLoader { 
    static getInstance<T>(context: Object, name: string, rawJson:any): T { 
        var instance:T = Object.create(context[name].prototype); 
        for(var attr in instance){ 
         instance[attr] = rawJson[attr]; 
        return <T>instance; 
InstanceLoader.getInstance<User>(this, 'User', JSON.parse('[{"lastName":"Nayrolles","firstName":"Mathieu"}]')[0]) 

InstanceLoader will only work when used inside an HTML page, as it depends on the window variable. If you try to execute it using ts-node, you'll get the following error:

    ReferenceError: window is not defined

Inheritance and polymorphism

Let's assume that we have a simple inheritance hierarchy as follows. We have an interface Animal that defines the eat():void and sleep(): void methods:

interface Animal{ eat():void; sleep():void; }

Then, we have a Mammal class that implements the Animal interface. This class also adds a constructor and leverages the private name: type notation we saw earlier. For the eat():void and sleep(): void methods, this class prints "Like a mammal":

class Mammal implements Animal{ 
   constructor(private name:string){ 
         console.log(this.name, "is alive"); 
         console.log("Like a mammal"); 
         console.log("Like a mammal"); 

We also have a Dog class that extends Mammal and overrides eat(): void so it prints "Like a Dog":

class Dog extends Mammal{ 
         console.log("Like a dog") 

Finally, we have a function that expects an Animal as a parameter and invokes the eat() method:

let mammal: Mammal = new Mammal("Mammal"); 
let dolly: Dog = new Dog("Dolly"); 
let prisca: Mammal = new Dog("Prisca");  
let abobination: Dog = new Mammal("abomination"); //-> Wait. WHAT ?! 
function makeThemEat (animal:Animal):void{ 

The output is as follows:

    ts-node class-inheritance-polymorhism.ts
    Mammal is alive
Dolly is alive
Prisca is alive
abomination is alive
Like a mammal
Like a dog
Like a dog
Like a mammal

Now, our last creation, let abomination: Dog = new Mammal("abomination"); should not be possible as per object-oriented principles. Indeed, the left-hand side of the affectation is more specific than the right-hand side, which should not be allowed by the TypeScript compiler. If we look at the generated JavaScript, we can see what happens. The types disappear and are replaced by functions. Then, the types of the variables are inferred at creation time:

var __extends = (this && this.__extends) || function (d, b) { 
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; 
    function __() { this.constructor = d; } 
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); 
var Mammal = (function () { 
    function Mammal() { 
    Mammal.prototype.eat = function () { 
        console.log("Like a mammal"); 
    Mammal.prototype.sleep = function () { 
        console.log("Like a mammal"); 
    return Mammal; 
var Dog = (function (_super) { 
    __extends(Dog, _super); 
    function Dog() { 
        _super.apply(this, arguments); 
    Dog.prototype.eat = function () { 
        console.log("Like a dog"); 
    return Dog; 
function makeThemEat(animal) { 
var mammal = new Mammal(); 
var dog = new Dog(); 
var labrador = new Mammal(); 
When in doubt, it's always a good idea to look at the transpiled JavaScript. You will see what's going on at execution time and maybe discover other pitfalls! As a side note, the TypeScript transpiler is fooled here because, from a JavaScript point of view, Mammal and Dog are not different; they have the same properties and functions. If we add a property in the Dog class (such as private race:string), it won't transpile anymore. This means that overriding methods are not sufficient to be recognized as types; they must be semantically different.

This example is a bit far-fetched, and I agree that this TypeScript specificity won't haunt you every day. However, if we are using some bounded genericity with a strict hierarchy, then you have to know about it. Indeed, the following example, unfortunately, works:

function makeThemEat<T extends Dog>(dog:T):void{ 


In this chapter, we completed a TypeScript setup and reviewed most of the best practices in terms of code convention, features we should and shouldn't use, and common pitfalls to avoid.

In the next chapter, we will focus on Angular and how to get started with the all-new Angular CLI.

About the Author

  • Mathieu Nayrolles

    Mathieu Nayrolles was born in France and lived in a small village in Côte d'Azur for almost 15 years. He started his computer science studies in France and continued in Montréal, Canada, where he now lives with his wife. Mathieu holds a PhD in electrical and computer engineering from Concordia University and two master degrees from eXia.Cesi (software engineering) and UQAM (computer science).

    Despite his academic journey, Mathieu also worked for worldwide companies such as Ubisoft, Eurocopter, Ericsson, or Saint-Gobain, where he learned how important good technical resources are.

    You can discover some of his works through his books: Expert Angular, Xamarin Studio for Android Programming: A C# Cookbook, Mastering Apache Solr: A practical guide to get to grips with Apache Solr, Instant Magento Performances, Magento Performance Optimization: How to, and Mastering Apache.

    Browse publications by this author

Latest Reviews

(5 reviews total)
Poor quality of the patterns
Book handels the pattern well
Just got started so can't really review completely. Like it so far.
Angular Design Patterns
Unlock this book and the full library for FREE
Start free trial