Grundlagen - Ökosystem

ES5 / ES6 / TS

ES5

  • JavaScript das alle modernen Browser unterstützen
  • neuere Versionen werden meist nach ES5 kompiliert / transpiliert

ES6 / ES2015

  • Neuere Version aus dem Jahr 2015
  • Wird meist mit Babel oder dem Google Closure Compiler zu ES5 transpiliert
  • Klassen, Arrow Funktionen, Block scoped let und const, Module, Multiline Strings...

TypeScript

  • Von Microsoft entwickelte Erweiterung
  • Wird mit dem TypeScript Compiler zu JavaScript kompiliert
  • Typisierung, Annotationen / Decorator, Interfaces, Generics

ES6 & Funktionen

ES6 Neuerungen

Fat arrow functions

                
                    // old way
                    [1, 2, 3].map(function (number) {
                       return number * 2;
                    });
                    // [2, 4, 6]
                     
                    // ES6 way
                    [1, 2, 3].map(number => number * 2);
                    // [2, 4, 6]
                     
				
            

Block scoped let

                    
                         // old way
                         for (var i = 0; i < 2; i++) {
                            // mach etwas
                         }
                         console.log(i);   // 1

                         
                         // ES6 way
                         for (let i = 0; i < 2; i++) {
                            // mach etwas
                         }
                         console.log(i);   // i is not defined 
                        
                    
            

var vs. let vs. const

  • var ist function scoped
  • let und const sind block scoped
  • let ist the new var ;-)
  • const ist ähnlich wie das final in Java
  • Achtung! Objekte oder Arrays können durchaus mutiert werden! (siehe final)

Objekt Literale

                 
                     let lastName = "Muster";
                     let obj = {
                        firstName: "Hans",
                        lastName,
                        hobbies: ["Tennis", "Lesen"]
                     };

                     let obj = {};
                     obj.firstName = "Hans";
                     obj.lastName = "Muster";
                     obj.hobbies = ["Tennis", "Lesen"];
				 
            

Template Strings

Werden mit dem Backtick ` erzeugt

                 
                     let name = 'Hans';
                     let templString = `Hallo
                        ${name},
                        wie geht es dir?`
                     console.log(templString); // Hallo
                                               // Hans,
                                               // wie geht es dir?
				 
            

Rest & Spreading

Rest Parameter

                     
                         function info(name, ...hobbies) {
                            hobbies.forEach(hobby => console.log(hobby));
                         }
                         info("Hans", "Tennis", "Squash", "Schach");
                         
                         // "Tennis" "Squash" "Schach"
                         
                         function multiply(multi, ...numbers) {
                            return numbers.map(num => multi * num);
                         }
                         console.log(multiply(2, 3, 4, 5, 6));
                         
                         // [6, 8 , 10, 12]
                         
                     
                

Spread Operator

                     
                         // Arrays kopieren
                         let arr = [1, 2]
                         let newArr = [...arr]
                         
                         // Arrays zusammenführen
                         let devs = ["Hans", "Reto"];
                         let testers = ["Peter", "Nicole"];
                         let employees = ["El jefe", ...devs, ...testers];
                         console.log(employees);
                         // ["El jefe", "Hans", "Reto", "Peter", "Nicole"]
                         

                         let today = [2017, 2, 29];
                         console.log(new Date(...today).toDateString());
                         // Wed Mar 29 2017
                        
                     
                

Default Parameter

Wenn Parameter nicht übergeben werden oder undefined sind

                 
                     function fullName(first = "Hans", last = "Muster") {
                        return first + ' ' + last;
                     }
                     console.log(fullName("Peter")); // "Peter Muster"
				 
            

Destructuring

Daten aus Arrays extrahieren

                     
                         let arr = [1, 2, 3];
                         let [a, b] = arr;
                         console.log(a); // 1
                         console.log(b); // 2

                         
                         let arr = [1, 2, 3, 4, 5];
                         let [a, , ...rest] = arr;
                         console.log(a); // 1
                         console.log(rest); // [3, 4, 5]
                         
                     
                 

Daten aus Objekten extrahieren

                     
                         let obj = {
                            firstName: "Hans",
                            lastName: "Muster",
                            hobbies: ["Tennis", "Lesen"]
                         };

                         let {firstName, hobbies} = obj;
                         console.log(firstName); // "Hans"
                         console.log(hobbies); // ["Tennis", "Lesen"]

                         let {firstName: vorname} = obj;
                         console.log(vorname); // "Hans"
                         
                     
                 

Funktionen als First Class Objekte

Zuweisung

                     
                         let func = function() {
                            // mach etwas
                         }
                         // nicht anonym - praktisch beim debuggen
                         let func = function funcName() {
                            // mach etwas
                         }
                        
                        // seit ES6
                        let es6Func = () => console.log("Hello");
                        es6Func(); // "Hello"
                        let add = (a, b) => a + b;
                        console.log(add(3, 4)); // 7
                        
                     
                 

Zuweisung (2)

                     
                        // Bei einem Parameter ohne Klammern möglich
                        let potenz = n => n * n;
                        console.log(potenz(4)); // 16
                     
                 

Funktionen als Return value

                     
                         let addThree = (a) => (b) => (c) => a + b + c;
                         console.log(addThree(1)(4)(3)); // 8

                         // oder in ES5
                         var addThreeOld = function addThreeOld(a) {
                            return function(b) {
                                return function (c) {
                                    return a + b + c;
                                }
                            };
                         };
                         console.log(addThreeOld(1)(4)(3)); // 8

                         // Ohne Klammern ;-)
                         let addThree = a => b => c => a + b + c;
                     
                 

Funktionen als Parameter

                     
                         function renderCustomer(c) {
                           console.log(c); // "Hans Muster"
                         }

                         function getFullName(name, callback) {
                           let lastName = 'Muster';
                           callback(name + ' ' + lastName);
                         }

                         getFullName("Hans", function(result) {
                            return renderCustomer(result);
                         });
                         
                         getFullName("Hans", renderCustomer);
                         
                     
                 

JS Besonderheiten

Truthy und Falsy

  • false
  • 0
  • "" (empty string)
  • null
  • undefined
  • NaN

Null checks & Triple equals

                 
                     let customer = getCustomer();
                     if(customer === null || customer === undefined) {
                        // do sth.
                     }

                     if(!customer) {
                        // do sth.
                     }
                 
             

TypeScript Features

Klassen

Constructor / shorthand

                 
                     class CustomerComponent {
                        constructor(private service: Service) {
                        }

                        findAll() {
                            return this.service.findAll();
                        }
                     }
                 
             

Getter / Setter Syntax

                     
                         class CustomerService {
                            private _customers: Customer[] = [{name: "Hans"}];
                            get customers() {
                                return this._customers;
                            }
                            set customers(customers: Customer[]) {
                                this._customers = customers;
                            }

                            extractName(customer: Customer) {
                                return customer.name;
                            }

                            getCustomerNames() {
                                return this.customers.map(extractName);
                            }
                         }
                     
                 

Typen

Typ Java Typ TypeScript
Object any
void void
boolean boolean
int, long, short... number
String, char string
Type[] Type[] / Array<Type>

Typisierung - Interfaces

                     
                         interface Customer {
                            hobbies: string[]
                         }
                         let validCus: Customer = {
                            hobbies: ["Tennis", "Squash"]
                         }

                         // Type '{ hobbies: string; }' is not assignable to
                         // type 'Customer'. Types of property 'hobbies' are
                         // incompatible. Type 'string' is not assignable
                         // to type 'string[]'.
                         let compileError: Customer = {
                            hobbies: "Tennis"
                         }
                     
                 

optional properties

                     
                         interface Customer {
                            mandatory: string;
                            optional?: string[]
                         }

                         let validCus: Customer = {
                            mandatory: "Mandatory"
                         }

                         // type '{ optional: string; }' is not assignable to
                         // type 'Customer'. Property 'mandatory' is missing
                         // in type '{ optional: string; }'.
                         let compileError: Customer = {
                            optional: ["Optional", "Prop"]
                         }
                     
                 

Funktionen in Interfaces

                     
                         interface Customer {
                            mandatory: string;
                            optional?: string[];
                            fullName: (first: string, last: string) => string;
                         }

                         let customer: Customer = {
                             mandatory: "Hans",
                             fullName(first, last) {
                                 return first + " " + last;
                             }
                         }
                     
                 

Union Types

                     
                         function printAge(age: number | string) {
                            console.log(age);
                         }

                         printAge(1); // 1
                         printAge("1"); // 1

                         // Argument of type 'number[]' is not assignable
                         // to parameter of type 'string | number'.
                         printAge([1, 2, 3])
                     
                 

Type Inference

                 
                     class Service {
                        private url = "/api";

                        createFullUrl(endpoint: number) {
                            //Type 'number' is not assignable to type 'string'
                            this.url = endpoint;
                            return 'localhost' + this.url;
                        }

                        getCustomerUrl() {
                            // Argument of type 'string' is not
                            // assignable to parameter of type 'number'.
                            return this.createFullUrl('customer');
                        }
                    }
                 
             

Module

Export

                     
                         export const API_URL = '/api';
                         export interface Person = {
                            name: string;
                         }
                         export function add(a: number, b: number) {
                            return a + b;
                         }
                         export const addFive(a: number) => a + 5;
                         export class Customer {
                            name: string;
                            constructor() {}
                         }
                     
                 

Import

                     
                         // wie Destructuring ;-)
                         import {Customer, Person} from "./customer";
                         import {Component} from "@angular/core";

                         let customer = new Customer();
                         let person: Person = {
                            name: "Hans"
                         }

                         import 'rxjs/add/operator/map';

                         import * as alias from "./exports";

                         let addFunc = alias.addFive;
                     
                 

node.js & npm

node.js

  • JavaScript runtime environment
  • Server Scripting mit JavaScript
  • Mittlerweile weit verbreitet, Stichwort: Full-Stack JS

npm

  • Steht für node package manager
  • Ein Teil von node.js (Wird mitinstalliert)
  • Vergleichbar mit Maven für Java

Aufgabe 2.1

  • Installiere node.js auf Deinem Rechner
  • node.js Download-Seite
  • Für Unix-Basierte Plattformen kann die Installation auch über einen Package Manager erfolgen
    • Z.B. HomeBrew für macOS

Version überprüfen

                    
                        $> node -v
                        $> npm -v
                    
                

Aktuelle node.js Version: v8.9.1

Aktuelle npm version: 5.5.1

Angular CLI

Angular CLI

  • Command Line Interface für Angular Projekte
  • Nützliche Commands zum...
    • Erstellen, Builden, Testen und Ausführen von Projekten
    • Erstellen von Komponenten, Direktiven, Services, etc.
    • u.v.m → Siehe Angular CLI auf GitHub

Aufgabe 2.2

Installiere das Angular CLI über npm

                    
                        $> npm install -g @angular/cli
                    
                

Auf -g achten → Globale Installation

Testen ob alles geklappt hat

                    
                        $> ng help
                    
                

Nützliche Links

Question Time!