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

Angular Design Patterns
By :

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:
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.
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; }else{ 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{ id:number; email:string; name:string; lastname:string; country:string; registerDate:string; key:string; 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, 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{
gender:Gender;
}
enum Gender{
MALE, FEMALE
}
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) { console.log('nothing'); } } 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.
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){
}
hello(){
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:
json.ts:19 userFromJSONAPI.hello(); ^ 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); })[0];
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]; console.log(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
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"); } eat(){ console.log("Like a mammal"); } sleep(){ 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{ eat(){ 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{ animal.eat(); }
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; }(Mammal)); function makeThemEat(animal) { animal.eat(); } var mammal = new Mammal(); var dog = new Dog(); var labrador = new Mammal(); makeThemEat(mammal); makeThemEat(dog); makeThemEat(labrador);
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{ dog.eat(); } makeThemEat<Mammal>(abomination);
Change the font size
Change margin width
Change background colour