Post/Code

HomeAboutUsesNow

TypeScript Basics.

function LogBook() { 
    this.trips = [];
}

LogBook.prototype.addTrip = function (trip) {
    this.trips = this.trips.concat([trip]);
    //immutable way of adding - Angular favours this. 
    // Alternatvie to this.trips.push(trip);
};

LogBook.prototype.removeTrip = function (trip) { 
    this.trips = this.trips.filter(function (log) { 
        return trip !== log;
    })
}

var myLog = new LogBook();

myLog.addTrip(43);
myLog.addTrip(7);
myLog.addTrip(29);

console.log("My Log: ", myLog);
console.log(typeof (myLog));
console.log("My Trips: ", myLog.trips);

myLog.removeTrip(7);

console.log("My Trips: ", myLog.trips);

// ES6/2015 class - TS Classes

class ShoppingList { 

    groceries: string[]; // array of string

    constructor() { 
        this.groceries = [];
    }

    // Public property on ShoppingList class
    addItem(item) {
        // Use ES6 spread operator to add item, alternative to concat and push
        this.groceries = [...this.groceries, item];
     }

    removeItem(item) {
        // implicit return using an ES6 arrow function
        this.groceries = this.groceries.filter((grocery) => item !== grocery);
        // same as in Trips 
        
     }
}

const myList = new ShoppingList();

myList.addItem("Apple");
myList.addItem("Banana");

console.log(myList.groceries);

myList.removeItem("Apple");

console.log(myList.groceries);