Angular2 – Typescript

Introduction

TypeScript is a superset to JavaScript, which means, that it compiles into pure JavaScript in the end.

Why do we use it then? First, it provides ‘strong typing’ (that’s where the name comes from). This means that we can (and should) assign types to our variables and class members. These types won’t compile to JavaScript (as JS does not know types) but we will get compilation errors if we assign wrong types or make any other type-related errors. This is a HUGE help in the daily development work and should not be underestimated!

Second, TypeScript introduces some nice features, JS does not have out of the box (at least in the ES5 specification). This includes classes (‘class’ keyword), interfaces, generics and modules. Being able to use these constructs makes our code cleaner, easier to read and helps us avoid nasty errors. Especially in combination with the strong typing we are really able to write high quality code and track down errors quickly.

Where can I learn all the TypeScript fundamentals?

There are a lot of great resources out there which will get you started very quickly. The official documentation is not too bad to be honest, so you may give it a try: http://www.typescriptlang.org/Handbook

There’s also a course here on Udemy, though I have not tested it! https://www.udemy.com/typescript/

Can we mix TypeScript and JavaScript?

Yes, we can. No one is preventing us from not setting types, using ‘var’ instead of ‘let’ or using pure JavaScript libraries (i.e. libraries which don’t offer a TypeScript version/ implementation).

Can’t I use ‘normal’ JavaScript to write Angular 2 applications?

You can absolutely do that. But currently finding good documentation and examples on Angular 2 using plain JavaScript is extremely hard. And to be honest: TypeScript will be the standard ‘language’ to be used when developing Angular 2 applications. So I definitely recommend using TypeScript.

Using types

  • We can define type for variables. Example:

01-typing/typing.ts

// Declaring a variable with a type
// Using the 'let' keyword to create a variable ('const' would define an immutable constant)
let myString: string;
myString = 'This is a string';
  • If we try to assign a different type will get an error on the typescript compiler
// Declaring a variable with a type
// Using the 'let' keyword to create a variable ('const' would define an immutable constant)
let myString: string;
myString = 'This is a string';

// Try to assign a number to a string => Error
myString = 4;
> tsc typing
typing.ts(10,1): error TS2322: Type '4' is not assignable to type 'string'
  • Typescript can also infer types. So in this example will also get an error:
// TypeScript can also infer types
let anotherString = 'This is a string without :string'; // => Type 'string' was inferred from the assigned value

// This will still resolve in a compilation error
anotherString = 4;
  • WARNING: Infering the type doesnt work if we not assign a value in declaration
// TypeScript may only infer values when those values are assigned at the declaration
// This does not work:
let yetAnotherString;
yetAnotherString = 'This is a string';

// TypeScript does not know the type, therefore we don't get an error ... but no we're also ignoring TypeScripts strength: Typing
yetAnotherString = 5;
  • By default if we dont specify type in the declaration will get the type any.
let yetAnotherString: any;
  • Other basic types:
// Other basic types

let aString: string;
let aNumber: number;
let aBoolean: boolean;
let anArray: Array<string>; // This is a generic type => May only hold 'strings' in this case
let anything: any; // Any can be used if we don't know the actual type => Use it rarely!
// We also got void (=> nothing) and enums (a set of numeric values)
  • We can also create custom types.
  • Summary : Strong types your variables: prevent errors.

 

Classes

// Classes allow us to create 'blueprints' for objects
// In Angular 2 we use classes a lot. For example to create Components, Services, Directives, Pipes, ...

// How to create a class

class Car {
    engineName: string;
    gears: number;
    private speed: number;

    constructor(speed: number) {
        this.speed = speed || 0;
    }

    accelerate(): void {
        this.speed++;
    }

    throttle():void {
        this.speed--;
    }

    getSpeed():void {
        console.log(this.speed);
    }

    static numberOfWheels(): number {
        return 4;
    }
}

// Instantiate (create) an object from a class

let car = new Car(5);
car.accelerate();
car.getSpeed();

console.log(Car.numberOfWheels());

* In old Javascript we already got class but now with TS use of classes is easier.

  • We can define private properties accessible from outside. By default are public
  • Static methods for been called for the class not for the instance. Yo dont need to create an object to call it:
    console.log(Car.numberOfWheels());

 

Interfaces

// Interfaces allow us to create contracts other classes/ objects have to implement
// We can use them to define custom types without creating classes
// Interfaces ARE NOT compiled to JavaScript! It's just for checking/ validation done by our TypeScript compiler

// Example interface

interface User {
    username: string;
    password: string;
    confirmPassword?: string; // Optional property => Does not have to be implemented
}

let user:User;

// This value does not satisfy the interface => Compilation error
// user = { anything: 'anything', anynumber: 5};

// This value does satisfy the interface
user = {username: 'max', password: 'supersecret'};

// Interfaces can also contain functions (without the function body - as it only is a blueprint/ requirement)

interface CanDrive {
    accelerate(speed:number): void;
}

let car:CanDrive = {
    accelerate: function (speed:number) {
        // ...
    }
};

Generics

  • Generic types allow us to be flexible with typing.
// Generics are types which can hold/ use several types
// We're only touching the very basics here - you can go MUCH more into detail

// Consider the Array object

let numberArray: Array<number>; // This array will only accept numbers

// Try to initialize it with strings

// numberArray = ['test']; // => Error
numberArray = [1,2,3];

 

 

Wrap up & modules

// TypeScript is modular, we can divide our code up over several files
// In Angular 2 we then use  "import {} from ''" to access the code in these files

// We export a class, interface, variable, ... by adding 'export' keyword in front of it

export class ExportedClass {
    // This class is exported
}

Deep dive into TypeScript

How to learn TypeScript

Throughout this course we’re always using TypeScript and I am convinced that you’ll be able to learn it ‘on the fly’. But a little head start is never wrong.

What is TypeScript?

TypeScript is a superset to JavaScript, which means, that it compiles into pure JavaScript in the end. Why do we use it then?

First, it provides ‘strong typing’ (that’s where the name comes from). This means that we can (and should) assign types to our variables and class members. These types won’t compile to JavaScript (as JS does not know types) but we will get compilation errors if we assign wrong types or make any other type-related errors. This is a HUGE help in the daily development work and should not be underestimated!

Second, TypeScript introduces some nice features, JS does not have out of the box (at least in the ES5 specification). This includes classes (‘class’ keyword), interfaces, generics and modules. Being able to use these constructs makes our code cleaner, easier to read and helps us avoid nasty errors. Especially in combination with the strong typing we are really able to write high quality code and track down errors quickly.

Where can I learn all the TypeScript fundamentals?

There are a lot of great resources out there which will get you started very quickly.

The official documentation is not too bad to be honest, so you may give it a try: http://www.typescriptlang.org/Handbook

There’s also a course here on Udemy, though I have not tested it! https://www.udemy.com/typescript/

Can we mix TypeScript and JavaScript?

Yes, we can. No one is preventing us from not setting types, using ‘var’ instead of ‘let’ or using pure JavaScript libraries (i.e. libraries which don’t offer a TypeScript version/ implementation).

Can’t I use ‘normal’ JavaScript to write Angular 2 applications?

You can absolutely do that. But currently finding good documentation and examples on Angular 2 using plain JavaScript is extremely hard. And to be honest: TypeScript will be the standard ‘language’ to be used when developing Angular 2 applications. So I definitely recommend using TypeScript