Ionic Code

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Budget Planner</title> <link rel="stylesheet" href="https://unpkg.com/@ionic/core@latest/css/ionic.bundle.css" /> <script src="https://unpkg.com/@ionic/core@latest/dist/ionic.js"></script> </head> <body> <ion-app> <ion-header> <ion-toolbar color="light"> <ion-title>Budget Planner</ion-title> </ion-toolbar> </ion-header> <ion-content> <ion-grid> <ion-row> <ion-col size-md="6" offset-md="3"> <ion-card> <ion-card-header> <ion-card-title>New Expense</ion-card-title> </ion-card-header> <ion-card-content> <ion-item> <ion-label position="floating">Expense Reason</ion-label> <ion-input type="text" id="input-reason"></ion-input> </ion-item> <ion-item> <ion-label position="floating">Expense Amount</ion-label> <ion-input type="number" id="input-amount"></ion-input> </ion-item> <div margin-vertical text-right> <ion-button fill="outline" color="danger" id="btn-cancel"> <ion-icon slot="start" name="close"></ion-icon >Clear</ion-button > <ion-button id="btn-confirm"> <ion-icon slot="start" name="add"></ion-icon> Add Expense </ion-button> </div> </ion-card-content> </ion-card> </ion-col> </ion-row> </ion-grid> </ion-content> </ion-app> <script src="app.js"></script> </body> </html>

Classes

Class structure

class Department { // private readonly id: string; // private name: string; protected employees: string[] = []; constructor(private readonly id: string, public name: string) { // this.id = id; // this.name = n; } describe(this: Department) { console.log(`Department (${this.id}): ${this.name}`); } addEmployee(employee: string) { // validation etc // this.id = 'd2'; this.employees.push(employee); } printEmployeeInformation() { console.log(this.employees.length); console.log(this.employees); } } class ITDepartment extends Department { admins: string[]; constructor(id: string, admins: string[]) { super(id, 'IT'); this.admins = admins; } } class AccountingDepartment extends Department { private lastReport: string; get mostRecentReport() { if (this.lastReport) { return this.lastReport; } throw new Error('No report found.'); } set mostRecentReport(value: string) { if (!value) { throw new Error('Please pass in a valid value!'); } this.addReport(value); } constructor(id: string, private reports: string[]) { super(id, 'Accounting'); this.lastReport = reports[0]; } addEmployee(name: string) { if (name === 'Max') { return; } this.employees.push(name); } addReport(text: string) { this.reports.push(text); this.lastReport = text; } printReports() { console.log(this.reports); } } const it = new ITDepartment('d1', ['Max']); it.addEmployee('Max'); it.addEmployee('Manu'); // it.employees[2] = 'Anna'; it.describe(); it.name = 'NEW NAME'; it.printEmployeeInformation(); console.log(it); const accounting = new AccountingDepartment('d2', []); accounting.mostRecentReport = 'Year End Report'; accounting.addReport('Something went wrong...'); console.log(accounting.mostRecentReport); accounting.addEmployee('Max'); accounting.addEmployee('Manu'); accounting.printReports(); accounting.printEmployeeInformation(); // const accountingCopy = { name: 'DUMMY', describe: accounting.describe }; // accountingCopy.describe();

Type Aliases

Type aliases create a new name for a type. Type aliases are sometimes similar to interfaces, but can name primitives, unions, tuples, and any other types that you’d otherwise have to write by hand.

type Combinable = number | string; type ConversionDescriptor = 'as-number' | 'as-text'; function combine( input1: Combinable, input2: Combinable, resultConversion: ConversionDescriptor ) { let result; if (typeof input1 === 'number' && typeof input2 === 'number' || resultConversion === 'as-number') { result = +input1 + +input2; } else { result = input1.toString() + input2.toString(); } return result; // if (resultConversion === 'as-number') { // return +result; // } else { // return result.toString(); // } } const combinedAges = combine(30, 26, 'as-number'); console.log(combinedAges); const combinedStringAges = combine('30', '26', 'as-number'); console.log(combinedStringAges); const combinedNames = combine('Max', 'Anna', 'as-text'); console.log(combinedNames);

Literal Types

String literal types allow you to specify the exact value a string must have. In practice string literal types combine nicely with union types, type guards, and type aliases. You can use these features together to get enum-like behavior with strings.

function combine( input1: number | string, input2: number | string, resultConversion: 'as-number' | 'as-text' ) { let result; if (typeof input1 === 'number' && typeof input2 === 'number' || resultConversion === 'as-number') { result = +input1 + +input2; } else { result = input1.toString() + input2.toString(); } return result; // if (resultConversion === 'as-number') { // return +result; // } else { // return result.toString(); // } } const combinedAges = combine(30, 26, 'as-number'); console.log(combinedAges); const combinedStringAges = combine('30', '26', 'as-number'); console.log(combinedStringAges); const combinedNames = combine('Max', 'Anna', 'as-text'); console.log(combinedNames);

Union Types

Union types are closely related to intersection types, but they are used very differently. Occasionally, you’ll run into a library that expects a parameter to be either a number or a string. A union type describes a value that can be one of several types. We use the vertical bar (|) to separate each type, so number | string | boolean is the type of a value that can be a number, a string, or a boolean. If we have a value that has a union type, we can only access members that are common to all types in the union.

function padLeft(value: string, padding: any) { if (typeof padding === "number") { return Array(padding + 1).join(" ") + value; } if (typeof padding === "string") { return padding + value; } throw new Error(`Expected string or number, got '${padding}'.`); } padLeft("Hello world", 4);

Enums

Enums are global constraint identifiers. They allow us to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums

enum Role { ADMIN = 'ADMIN', READ_ONLY = 100, AUTHOR = 'AUTHOR' }; const person = { name: 'Maximilian', age: 30, hobbies: ['Sports', 'Cooking'], role: Role.ADMIN }; // person.role.push('admin'); // person.role[1] = 10; // person.role = [0, 'admin', 'user']; let favoriteActivities: string[]; favoriteActivities = ['Sports']; console.log(person.name); for (const hobby of person.hobbies) { console.log(hobby.toUpperCase()); // console.log(hobby.map()); // !!! ERROR !!! } if (person.role === Role.AUTHOR) { console.log('is author'); }

Arrays

This code sample shows how to create and iterate through arrays in Typescript.

const place = { name: 'Rio de Janeiro', age: 30, hobbies: ['Sports', 'Surfing'] }; let favoriteActivities: string[]; favoriteActivities = ['Sports']; console.log(person.name); for (const hobby of person.hobbies) { console.log(hobby.toUpperCase()); }

Functions

As seen in the previous example, we see how we create functions. We provide the function keyword and the name of the function. If parameters exist, we should specify the type of them after the variable and a colon.

function calculate(num1: number, word: string, isTrue: boolean) { console.log(num1 + word + isTrue); } calculate(30, "hi", true);

Types as Parameters

The types of the parameters in Typescript should be specified after a colon. An example is shown in the code where the variables, x and y are specified as strings.

function name(x: string, y: string) { return x + y } const firstWord = "Hi"; const secondWord = " how are you?"; const name = name(firstWord, secondWord); console.log(name);

Creating Typescript Variables

We have created variables of type number, string and boolean on lines 2-6. We have created them with the let keyword, meaning they can be modified. On lines 8-12, we've created the same type of variables preceded by const, meaning they have to stay constant and cannot be changed.

let number = 10; let word = "hello"; let isAllowed = true; const number2 = 15; const word = "hi"; const isAllowed = false;

Typeof Operator

The typeof operator returns a string representing the data type associated with the object.

let number = 24; console.log(typeof number); // expected output: "number" console.log(typeof 'hi'); // expected output: "string" console.log(typeof true); // expected output: "boolean"

Difference between Var, Let and Const variables

In Javascript, we primarily used variables with the 'var' declaration. Starting in ES6 and therefore in Typescript, we will be using let and var. Var and let can change their value and const cannot change its value. Var can be accessible anywhere in function but let and const can only be accessible inside the block where they are declared.

//ES5 var x = 14; x = 12; console.log(x);//12 //ES6 let x = 14; x = 12; console.log(x); //12 //ES6 const y = 14; y = 12; //TypeError: Assignment to constant variable. console.log(y);