TypeScript 3.1

Table of Contents :

What is TypeScript ?

What is TypeScript ?


Typescript Programming features:
1.Type script spec been built on top of ES 6 Standards
2.Type script offers rich type system
3.Type script offers extra features as well.

TypeScript = ES6 + Data Types + Extra Features.


TypeScript is compiled into plain javascript.

TS

Pre-requisites for TypeScript programming workspace setup :

Steps:

1.CREATE Folder – ts-app
2.move into that folder
ts-app>
3. npm init -> package.json file //It is used to set up a new or existing npm package.creates a package.json file.

4. Invoke Visual Studio Code
code .
5. install type script compiler
> npm install typescript –save-dev

npm config set proxy

TypeScript Compilation :

Write source code
->fileName.ts
Compile
>tsc fileName.ts
>fileName.js – output file(compiled file)
Setup:
package.json
“scripts”: {
“test”: “echo \”Error: no test specified\” && exit 1″,
“compile”: “tsc src/index.ts ”
},

npm run compile

run is command name
compile is task name
we can give any task name.

tsc is already installed in the project directory under node_modules.
Compile will lookup source entry points and compiled code is available.


Use case – 1 :



How to keep source program and compiled program in a separate directory
->src and build

How to tell the compiler that compiled code must be placed inside build folder.
-Compiler args

tsc source.ts –compiler args | -compiler args

–outDir : redirect output to given directory

“scripts”: {
“compile”: “tsc src/index.ts –outDir build”,
“test”: “echo \”Error: no test specified\” && exit 1″
},



Use case – 2 :

How to do enable auto compilation

Hot Reloading: The feature which helps to automate dev work flow
if i write code,then i press save button, code is saved
->compile-update complied code–reload code on target(browser/node)
when ever i change the code, it should get compiled automatically.

–watch =true / false

npm run compile -w

Use case – 3:

What if i want to add more and more compiler args?

As of now, we have added configuration inline, which is not recommended
so we need compiler configuration file.

How to create compiler configuration file?
tsconfig.json

Use case 4: what if the config file name is different other than tsconfig.json

>tsc
->tsconfig.json

tsdevconfig.json
tstestconfig.json
tsprodconfig.json
>tsc -project tsdevconfig.json

Variable Declaration & Data Types in TypeScript :

ar ->es 5
let,const ->ES 6

var variableName=value;
let | const variableName =value;

value : literals
1.string – ”,””,“
2.number
3.booleans -true or false
4.undefined
5.Infinity
6.NaN – Not a number
7.function
8.object
9.null

var name=’subramanian’
let name=’Subramanian’ -es 6
Strings;
String literals:
” – javascript style
“” – other language style
“ -back tick – es 6
-Use case for back tick:
1.complex string concatation

${domain} – template literal

import { servicesVersion } from “typescript”;

//variable declarations

let firstName = “Subramanian”;
console.log(“First Name” + firstName);
let lastName = ‘M’;
console.log(“Last Name” + lastName);
//back tick notation :“
console.log(`First Name ${firstName}`);
let htmldoc = “” +”” +
“” +
“” +”” +

Hello

” +

“;

let newDoc = `

Welcome

`;
let api = “api/sopra”;
let resource = “customers”;
let subresource = “list”
let domain = “sopra”
let url = “http://www.” + domain + “/” + api + “/” + resource + subresource;
let urlnew = `http://www.${domain}/${api}/${resource}/${subresource}`;

number
->64 bit -double

let salary = 10000;
console.log(`Salary ${salary}`);
//computation
let totalSalary = salary * 10;
console.log(`Total Salary ${totalSalary}`);

undefined :
The variable not initalized with valid literals(string,number,boolean,object,function,infinity…)
NaN: Not a Number: it is runtime error.
NaN Use case:

1.You will get NaN, if you do computation against “undefined”
Type conversion:
1.if you declare variable, and its value is string but content is number
“100”
if you computation “100” * 10 => 1000
Here “100” is converted or type casted into number and compuation takes
place – implicit type conversion

2.if you declare variable, and its value is string but content is number and
with special character
“100%”
if you do computation = “100%” * 10 =>NaN
Not a Number:
It is numerical error
It is runtime error
It is danagerous
let salary;
console.log(`Salary ${salary}`);

let totalSalary = salary * 100;
console.log(`Total Salary ${totalSalary}`);

let wage = “500”;
//let totalWage = wage * 7; //(string * number) //implict type conversion
let totalWage = parseInt(wage) * 7; //explicit type conversion
console.log(`Total Wage ${totalWage}`);

let stockValue = “$10”;
let qty = 10;
//let totalStockValue = stockValue * qty; //
let totalStockValue = parseInt(stockValue) * qty; //
console.log(`Total Stock Value ${totalStockValue}`);
booleans:
//booleans
let isWorking = true;
let isEnable = false;
console.log(`IsWorking ${isWorking}`);
console.log(`Is Enabled ${isEnable}`);
//decision making
if (isWorking) {
console.log(‘Working’)
} else {
console.log(`Left`);
}
//the above logic can be rewritten using tenary operator
isWorking ? console.log(‘Working’) : console.log(‘Left’);
//Advanced booleans
/**
* Truthy and falsy values:
* In javascript all values are true(truthy) except the below values(falsy values)
* 1.boolean false
* 2.0
* 3.empty string “”,”
* 4.undefined
* 5.NaN
* 6.null
*/

let status = ”;
if (status) {
console.log(‘Fine’)
} else {
console.log(‘Not fine!’);
}

//Infinity
let salary = 1000;
let avgSalary = salary / 0;
console.log(`Avg Salary ${avgSalary}`);

const :
//var vs let
//let vs const

let age =18;
console.log(`Age is ${age}`);
age =24;
console.log(`Age is ${age}`);

const PI = 3.14;
console.log(`PI is ${PI}`);
//PI=34.8;
console.log(`PI is ${PI}`);
const fname=’subramanian’;
console.log(`${fname}`)
//fname =’Ram’;

////////////////////////////////////////////////////////////////////////////

Use case : how to stop compiler by emitting code, if there is any compile
time error

By default ,ts compiler will emit code even though ,compiler produces error.

How to stop that?
tsconfig.json
“compilerOptions”: {
“noEmitOnError”: true,
}

Type system:

let a =10; //number
a=”test” // string
a=true //boolean

let Variable:type =value

Data types:

1.primitives
string,number,boolean
2.reference types
object

Syntax:
let | const | var variableName:type = value
eg
let firstName:string=’test’
firstName =90; //compiler will throw error
//type system
//primitives:number,string,boolean

let firstName: string = ‘Subramanian’;
let age: number = 18;
let isActive: boolean = true;
//type viloation
//firstName = 10;

//let salary = 1000; // type inference
let salary: number = 1000; //explicit typing
//salary = “x”;
//any means
let myvar: any = 10;
myvar = “test”
myvar = 90;

//undefined ==any
let mystatus; //undefined
mystatus = true;
mystatus = “hello”;

//: ‘const’ declarations must be initialized
//const PI;
const PI: undefined = undefined;
//PI = 90;
let mynewVar: undefined;
//mynewVar = 90;

Functions in TypeScript :

Functions:
functions are building block of javascript.

Use case : how to declare function and call function

function add() {
console.log(‘Add function’)
}
//call the function
add()

Use case : how to pass parameters to function and compute the parameters

function add(a, b) {
let result = a + b;
console.log(`The result is ${result}`);
}
add(2, 2);

Use case: Type inference and function parameters

with Undefined:
……………
function add(a, b) {
let result = a + b;
console.log(`The result is ${result}`);
}
add(2, 2);
add(“$4”, 5);

with any:
function add(a: any, b: any) {
let result = a + b;
console.log(`The result is ${result}`);
}
add(2, 2);
add(“34”, 2);

Use case: typed parameters and functions

function add(a: number, b: number) {
let result = a + b;
console.log(`The result is ${result}`);
}
add(2, 2);

add(“34”, 2);

//errors:
src/index.ts:15:5 – error TS2345: Argument of type ‘”34″‘ is not assignable to parameter of type ‘number’.
15 add(“34”, 2);

//functions

//declare
function sayHelo() {
console.log(‘Hello’);
}
//invoke
sayHelo();
//function with params
// function add(a, b) {
// let result = a + b;
// console.log(`The result is ${result}`);
// }
function add(a: number, b: number) {
let result = a + b;
console.log(`The result is ${result}`);
}
add(2, 2);
//add(); //error :no params
//add(“test”, true); // number,number

//return with type inference: based on return value the return type is inferenced
// function div(a: number, b: number) {
// //return 10; //number
// return “Hello” // string
// }
function div(a: number, b: number): number {
return a / b; //number
//return “Hello” // string
}
console.log(div(1, 2))
//any , or without any both are same
function greet(): any {
return ‘Greet’
}
//i dont want return value : void
function compute(): void {
console.log(‘Compute’);
//return 10;
return; //void-undefined
}
//let status1 = compute() ? ‘go’ : ‘dontGo’
//console.log(status1)
//default args:if you dont supply,the defaults can be supplied
function mul(a: number = 1, b: number = 1): number {
return a * b;
}
let result = 0;
result = mul(1, 2); //number,n=number
console.log(result);
result = mul(); //undefined ,undefined
console.log(‘new result’, result);
//optional parameters/args
function login(userName?: string, password?: string) {
console.log(`${userName} ${password}`)
}
login(‘admin’, ‘admin’);
login();
////////////////////////////////////////////////////////////////////////
Arrow functions and Lambdas:
……………………….

//arrow functions

//functions can be written in two ways
//way 1
function sayHello(): string {
return ‘Hello’;
}
sayHello();
//way 2
//function literals
let greet = function (message: string = ‘default’) {
//console.log(message);
return message
};
/**
* function can be assinged to a variable,that variable can be
* used to invoke that function
*/
console.log(greet(‘Greet’));
//arrow
//simple arrow function
let add = () => {
console.log(‘Add’);
};
add();
//if function has one line of body,drop {}
add = () => console.log(‘Add Function’);
add();
//if function takes more args
add = (a: number = 1, b: number = 1): void => console.log(`${a} ${b}`);
add();
//if function takes one arg without any implicit type
let getName = name => console.log(name);
getName(‘Subramanian’)
//////////////////////////////////////////////////////////////
//return values
let getStockValue = (): number => {
return 10;
};
console.log(getStockValue());
//if function only return , no more body
getStockValue = (): number => 10;
console.log(getStockValue());
//if function takes single parameter,no implicit type,return the same
let getNewStockValue = stock => stock;
console.log(getNewStockValue(10));

Object oriented Programming in Typescript :

functions:
first class citizens
functions are used to represent “unit of execution” – process -logic
eg: add,mul,div,login
functions are used to represent “heap memory-object” – state + behaviour
eg :Customer,Employee
functions are used to represent “Queue message-callback”-async programming

Object creations in js:

1.constructor pattern
1.1.using functions
1.2.using es 6 class

//Noun
// function Employee() {

// }
let emp1 = new Employee();

class Employee {

}

let emp = new Employee() // heap memory : Object

Object = state,behaviour,identity
state =>instance variable
behviour => instance methods
//declare class
class Employee {
//instance variables
id: number = 1;
name: string;
salary: number;
isWorking: boolean;
constructor(id?: number, name: string = ‘default’, salary: number = 100, isWorking: boolean = false) {
this.id = id;
this.name = name;
this.salary = salary;
this.isWorking = true;
}
//methods:functions
// calculateSalary(noofdays: number = 0): number {
// return this.salary * noofdays;
// }
calculateSalary = (noofdays: number = 0) => (this.salary * noofdays);

}
//create object
let emp = null; //constructor call
emp = new Employee();
//state initalization
emp.id = 10;
emp.name = ‘subramanian’;
emp.salary = 100;
emp.isWorking = true
console.log(`Id ${emp.id}`);
console.log(`Name ${emp.name}`);
console.log(`Salary ${emp.salary}`);
console.log(`IsWorking ${emp.isWorking}`);
console.log(`total salary ${emp.calculateSalary(12)}`)

//new object creation: with help of constructor parameters
emp = new Employee(23, ‘Ram’, 90, false) //constructor call
console.log(`Id ${emp.id}`);
console.log(`Name ${emp.name}`);
console.log(`Salary ${emp.salary}`);
console.log(`IsWorking ${emp.isWorking}`);
console.log(`total salary ${emp.calculateSalary(24)}`)
2.literal pattern

let customer = {
//state
id: 1,
name: ‘Subramanian’,
};
console.log(
`${customer.id} ${customer.name}`);

literal vs class: where to use in applications

literal is single ton: create,use,throw
class is factory :create more objects out of single class.

Angular or any framework specific use case:

1.classes are used to represent infra structure objects
like controller,service
2.literals are used to represent biz data-models
//creating object : literals patterns
/**
* no class /function templates
*/
let customer = {
//state
id: 1,
name: ‘Subramanian’,
calculateSalary: function () {
return 100;
},
calculateLeave: () => 10,
calculateBouns() {
return 1;
}
};
console.log(`${customer.id} ${customer.name}`);

Use case : how to add type to literal object’s instance variable

1.via class – Type class
class Customer {
id: number;
name: string;
city: string;
}

//literal’s state type

//1.via class – Type class
class Customer {
id: number;
name: string;
city?: string;
}
let customer: Customer = {
id: 1,
name: ‘subramanian’,
city: ‘Chennai’
};
//customer.id = “test”;

let newCustomer: Customer = {
id: 1,
name: ‘Ram’
}

Interfaces in TypeScript :
………..
interface is TS feature not ES6.

Role of Interfaces:
class based inheritance vs interface based inheritance

Objective: code reuse

Eg:
fly,land,takeOff
Bird —>Pe
Flight —

Interface in ts plays two roles
1.Inheritance -share common code across different type of objects
2.Act as common type

//literal’s state type

//1.via class – Type class
class Customer {
id: number;
name: string;
city?: string;
}
let customer: Customer = {
id: 1,
name: ‘subramanian’,
city: ‘Chennai’
};
//customer.id = “test”;

let newCustomer: Customer = {
id: 1,
name: ‘Ram’
}
//interface as type
interface Product {
id: number,
name: string;
}
let tv: Product = {
id: 1,
name: ‘Sony TV’
}
let food: Product = {
id: 2,
name: ‘Full Meals’
}
//inline type
const invoice: { no: number, value: number, shippingCity?: string } = {
no: 1,
value: 1000
}
//via type keyword
type Country = { code: number, name?: string };

const oman: Country = {
code: 100,
name: ‘Oman’
}
console.log(`code ${oman.code} name ${oman.name}`)

const india: Country = {
code: 200,
name: ‘India’
}
console.log(`code ${india.code} name ${india.name}`)

Enum in TypeScript :

Advanced types:
1.enum
//Enum : declaring named constants

enum FEEDBACK {
None,
Neat,
Cool,
Awesome
};
console.log(FEEDBACK.None)
console.log(FEEDBACK.Neat)