Before beginning with Ionic, it is essential to have good knowledge of Angular. Angular programs are written in TypeScript.
But before looking at TypeScript we will also take a brief look at Node JS. Node Js is a server environment that runs JavaScript. The easiest way to run TypeScript is within node.
Node comes with its package manager - npm - Node Package Manager. NPM is the world’s largest package repository. It is the most common mechanism to distribute open source software. TypeScript, Angular and Node are made available via node.
At the most fundamental level it is important to get a sense of what TypeScript is and what the programming language looks like. This is done best by means of practical examples. It is recommended that you try the examples in this tutorial before proceeding to Ionic.
From the TypeScript website...
As mentioned above, TypeScript is made available through node js. If you do not have node already installed, you can install it from:
https://nodejs.org/en/download/
Once you have node installed, you have node’s package manager available. TypeScript can be installed using:
TypeScript compiles to JavaScript and node executes the JavaScript files. To be precise, node is a JavaScript runtime environment, much like JRE for Java. It contains everything that JavaScript needs to run.
It is built on Chrome’s JavaScript V8 Engine. It converts JavaScript to Machine Code
What does the JavaScript V8 Engine do in Chrome/ Node
Each browser has its own JavaScript Engine. Chrome runs V8, Firefox runs SpiderMonkey, and Internet Explorer, Chakra. Each has its own compatibility issues.
https://kangax.github.io/compat-table/es6/
Angular 2 would is a complete rewrite of AngularJS, which was written in JavaScript. Microsoft added annotations to TypeScript language, and making it the language for the development of the Angular 2 framework itself.
Download and install Visual Studio Code from https://code.visualstudio.com/
With this background, we are good to get started with TypeScript. This will be a brief introduction so that we know enough to get introduced to Angular/ Ionic.
Hello World
In addition to doing a “hello world” in TypeScript, you now know how to import a folder and create files in TypeScript. You also now know how to run commands within the editor.
A variable is used to store, retrieve and manipulate information in a programming language. TypeScript uses the key words let and const to declare variables.
let greeting = “hello world” console.log(greeting) const greeting2 = “hello world” console.log(greeting2)
A variable declared using Const needs to be initialized and it cannot be reassigned.
In the images above, it is seen that Visual Studio Code flags the variable “a” with an error when it is not initialized and when it is reassigned a value.
TypeScript supports 3 data types. As mentioned earlier using data types is optional.
let name : string = “Josh” let age : number = 22 let isStudent : boolean = true
let name : string = null let name : string = undefined
An expression is a combination of operators and operands. Operands can be constants, variables or other expressions.
a= 12 * b + c;
12, b, c are operands in the expression and =,*,+ are operators.
TypeScript supports the following operators:
Arithmetic operators | +, -, *, /, %, ++, -- |
Logical operators | && (AND), || (OR), ! (NOT) |
Relational operators | >, <, >=, <=, != (not equal), == (equal) |
Assignment operators | =, +=, -=, *=, /=, %= |
Ternary/conditional operator | let t = 10>20?”smaller”:”larger”; Will store “smaller” in t |
TypeOf Operator | “ var a = 12; console.log(typeof a)” will return “number” |
Bitwise operators | & (AND). | (OR), ^ (XOR), ~ ( Not), << (Left Shift), >> (Right Shift), >>> (Right shift with Zero) |
Template Strings
A template string is a string which is enclosed within back-tick characters (`). It can include expressions within ${ }. TypeScript replaces placeholders with real values. Template strings are a better option to use when compared to string concatenation.
let name = 'Josh'; console.log('name ' + name) let statement = `I am ${name}` console.log(statement)
The output will be:
An array is a data structure that contains a group of elements. Typically these elements are all of the same data type, such as a number or string. Arrays are commonly used in computer programs to organize data so that a related set of values can be easily sorted or searched.
You can declare an array in 2 ways:
let list1 :number[] = [1,2,3] let list2: Array<number> = [1,2,3]
String arrays
let list3: Array<string> = ['1','2','3'] let list4: Array<string> = [`1 ${list2}`,'2','3'] console.log(list4)
Any is used when you are not sure what the data type is. When a variable is declared as “any” it can be assigned any value
let a :any; a = "200"; a = 200; a = false; console.log(a)
A tuple is an array of fixed length. It allows multiple types in a single array.
let student : [string,number] = ['josh',2]
console.log(student)
Type inference happens in TypeScript when there is no explicit data type specified and the variable is initialized.
The following will work
let a
a = true
a= 1
The following will throw an error since the type is inferred as number;
let a = 10
a = true
TypeScript allows multiple types for a single variable. You can achieve this by using the pipe symbol in the variable declaration. This is normally used when the data stored in the variable is not under your control.
In comparison to “any”, it allows a higher degree of control. It also provides intellisense support.
let a :number|string;
a=20;
a="zoom"
Below is the intellisense for a when is a union of number and string
Below is the intellisense when it is any
In any programming language, functions define how to do things.
function printHello(){ console.log('Hello') } printHello()
function printHello(message){ console.log(message) } printHello('hello')
function printHello(message:string){ console.log(message) } printHello('hello')
function printHello(message:string, name:string){ console.log(message + " " + name) } printHello('hello', 'josh')
function printHello(message:string, name?:string){ if(name) console.log(message + " " + name) else console.log(message ) } printHello('hello', 'josh') printHello('hello, how are you' )
The output will be
If a parameter is not passed, it can be initialized with a default value
function printHello(message:string = 'Hello', name?:string){ if(name) console.log(message + " " + name) else console.log(message ) } printHello()
A return type is defined as below
function printHello(message:string, name:string):string{ if(name) return message + " " + name else return message } let message = printHello("Hello", "Josh"); console.log(message);
A class is a template for an object and an object is an instance of a class.
Below is an example of a TypeScript class
class Person{ firstName:string; lastName:string; sayHello(){ console.log("hello " + this.firstName) } sayGoodBye(){ console.log("bye " + this.firstName) } }
An instance of the class is created as follows
let max = new Person(); max.firstName = "Max"; max.lastName = "Payne"; max.sayHello(); console.log(max);
Constructors are used to initialize classes. They are automatically called when the class is created
class Person{ firstName:string; lastName:string; constructor(firstName:string, lastName?:string){ this.firstName = firstName; this.lastName = lastName; } sayHello(){ console.log("hello " + this.firstName) } sayGoodBye(){ console.log("bye " + this.firstName) } } let max = new Person("Max", "Payne"); max.sayHello(); console.log(max);
A class can have optional properties as follows
lastName?:string;
Objects arrays can be initialized as follows:
let persons :Person[] = [{"firstName":"Quintin","lastName":"Tarantino"}, {"firstName":"Steven","lastName":"Spielberg"}, {"firstName":"Christopher","lastName":"Nolan"}]
They can be looped through using a for loop as follows
for(let i=0; i<persons.length; i++){ console.log(`${i} ${persons[i].firstName} ${persons[i].lastName}`) }
Or using a while loop
let i=0; while(i<persons.length){ console.log(`${i} ${persons[i].firstName} ${persons[i].lastName}`) i++; }
Interfaces specify “what” a class must do, but not “how”. They define the structure of a class.
interface Person{ firstName:string; lastName:string; sayHello(); sayGoodBye(); }
The implementation of sayHello and sayGoodBye is upto the classes that implement the interface to define. Class SimplePerson implements Person{ firstName:string; lastName:string; sayHello(){ console.log(“Simple Hello”; } sayGoodBye(){ console.log(“Simple Bye”; } } Class ComplexPerson implements Person{ firstName:string; lastName:string; sayHello(){ console.log(“Complex Hello”; } sayGoodBye(){ console.log(“Complex Bye”; } }
Modules are executed within their own scope, not in the global scope; this means that variables, functions, classes, etc. declared in a module are not visible outside the module unless they are explicitly exported from the module and imported into the program using them
In the above example, the interface Person will not be accessible unless it is imported.
export interface Person { firstName:string; lastName:string; sayHello(); sayGoodBye(); }
The class implementing the interface has to import the module
import { Person } from "./helloInterface"; class Person3 implements Person{
The key points to be noted here are the export keyword and import statement
TypeScript applies object oriented programming to JavaScript. The process of conversion of TypeScript to JavaScript is an example of transpilation.
One of the key advantages of transpilation is that it allows us to use future features of JavaScript today.
Leave a Reply
Your email address will not be published. Required fields are marked *