While doing we need to let know Typescript how the datatypes are defined.The definition files are available in internet and it should be added to the script folder while doing the casting

Suppose I am doing a casting HTMLElement while accessing DOMto HTMLInputElement i should add lib.d.ts which contains the definition for DOM elements.

In the below code document.getElementById(‘Name’) returns HTMLElement which is least specific compared to HTMLInputElement.

var name = <HTMLInputElement>document.getElementById('Name');
  1. Using Interface we can have blue print of list of things which needs to be implemented
interface calculateInterest {
    accountType: String,
    interest: number,
    depAmt?: number,
    calculateInt(depositAmt: number) : number;
} 

var IntForSavings: calculateInterest = {
    accountType: "Savings",
    interest: 12,     
    depAmt : 0,
    calculateInt: function (depositAmt:number) {
        this.depAmt = depositAmt;
        return depositAmt * this.interest;
    }    
};

var IntForCurrent: calculateInterest = {
    accountType: "Current",
    interest: 5,           
    depAmt: 0,
    calculateInt: function (depositAmt: number) {
        this.depAmt = depositAmt;
        return depositAmt * this.interest;
    }
};

var IntForLoans: calculateInterest = {
    accountType: "Loan Account",
    interest: 8,
    depAmt: 0,
    calculateInt: function (depositAmt: number) {
        this.depAmt = depositAmt;
        return depositAmt * this.interest;
    }
};

console.log(IntForSavings.accountType + ' yields ' + IntForSavings.calculateInt(12000) + ' for cash amount of ' + IntForSavings.depAmt);
console.log(IntForCurrent.accountType + ' yields ' + IntForCurrent.calculateInt(6000) + ' for cash amount of ' + IntForCurrent.depAmt);
console.log(IntForLoans.accountType + ' yields ' + IntForLoans.calculateInt(3000) + ' for cash amount of ' + IntForLoans.depAmt);

Output

Savings yields 144000 for cash amount of 12000
Current yields 30000 for cash amount of 6000
Loan Account yields 24000 for cash amount of 3000

Classes extending Interface
Accounts.ts

interface Accounts {
    accountType?: string;
    calculateInterest(accountType: string): number;
}

class SavingsAcc implements Accounts {
   
    minimumBalance: number = 10000;
    accountType: string = 'Savings';    

    calculateInterest(accountType: string): number{
        return 5;
    }
}

class CurrentAcc implements Accounts {
    minimumBalance: number;
    accountType: string = 'Current';
    calculateInterest(accountType: string): number {
        return 5;
    }
}

class LoanAcc implements Accounts {
    accountType: string = 'Loan';
    calculateInterest(accountType: string): number {
        return 12;
    }
}

class Customer {
    private _accountType: Accounts;          

    constructor(customerId: number, AccountType : Accounts) {
        this._accountType = AccountType;
    }

    public get accountType(): Accounts {
        return this._accountType;
    }
    public set accountType(value: Accounts) {
        this._accountType = value;
    }
}

window.onload = function () {
    var objCustomer: Customer = new Customer(1001, new LoanAcc());    
    console.log(objCustomer.accountType.accountType + ' Account with interest rate of ' + objCustomer.accountType.calculateInterest('Loan'));


    var objCustomer: Customer = new Customer(1001, new SavingsAcc());
    console.log(objCustomer.accountType.accountType + ' Account with interest rate of ' + objCustomer.accountType.calculateInterest('Savings'));
}

Output

Loan Account with interest of 12
Savings Account with interest of 5

Accessing property of class extending Interface
We have the same code of Accounts.ts with slight modification on window.load. We try to access a property specific to class implementing interface.
In the below code minimumBalance is a property specific to savingsAccount which implements Accounts. In such case we need to do type case from generic interface object to specific class object
so the property specific to class is available.

window.onload = function () {
    var objCustomer: Customer = new Customer(1001, new SavingsAcc());
    var objSavingAcc: SavingsAcc = <SavingsAcc>objCustomer.accountType;
    console.log(objCustomer.accountType.accountType + ' Account with interest rate of ' + objCustomer.accountType.calculateInterest('Savings') + ' with minimum balance of ' + objSavingAcc.minimumBalance);
}

Output

Savings Account with interest rate of 5 with minimum balance of 10000

Using Interface to write clean code
One of the advantage of interface is while passing multiple arguments to constructor we can avoid the misplacement of the argument passed
like the one in code below. This is similar to ENUM in Java. The the Account class constructor we can change the arguments to interface as follows

Interfaces.ts

interface IPerson {
    name: string;
    age: number;
    location: string;
}

interface IEmployee extends IPerson{
    empId: number;
}

interface ICustomer extends IPerson {
    custId: number;
    accType: string;
}

Account.ts

class Account {
    private _name: string;
    private _age: number;
    private _location: string;    
    private _custId: number;   
    private _accType: string;   

    constructor(name: string, age: number, location: string, custId: number, accType: string) {    
        this._name = name;
        this._age = age;
        this._location = location;
        this._custId = custId;
        this._accType = accType;
    }
}

Refactored Account class with constructor arguments changed to inteface

Account.ts

class Account {
    private _name: string;
    private _age: number;
    private _location: string;    
    private _custId: number;   
    private _accType: string;   

    constructor(iPerson: ICustomer) {
        this._name = iPerson.name;
        this._age = iPerson.age;
        this._location = iPerson.location;
        this._custId = iPerson.custId;
        this._accType = iPerson.accType;
    }
}

Functions using arrow function Expression

var multiply = function (num: number) {
        return num * num;
}

The same above function could be written using arrow key expression as below

var multiply = (num1: number, num2: number) => return num1 * num2;

//With flower braces in case of multiple statements
var multiply = (num1: number, num2: number) => {return num1 * num2;};

we can also do function declaration and definition in two separate lines as one below

//function declaration
var multiply: (num1: number, num2: number) => number;    

//function definition
multiply = function (num1: number, num2: number) {
  return num1 * num2;
}

//function taking object literals as arguments
var multiply: (numbs: { num1: number, num2: number }) => number;    
var numbs = { num1: 2, num2: 4 };

multiply = function (numbs) {
   return numbs.num1 * numbs.num2;
}
  1. What is difference between let and var while declaring variable?
    var is Function Scoped and let is block scoped
    Using var

    var foo = 123;
    if (true) {
        var foo = 456;
    }
    
    console.log(foo); // 456
    

    Using let

    let foo = 123;
    if (true) {
        let foo = 456;
    
    }
    console.log(foo); // 123
    
  2. What would be the value of the below variables?
     
     //Value is Undefined
     var foo:string;
     
     //You can explicitly define value as undefined 
     var age = undefined;
    
     //any is a valid value which is default type until the variable assumes some data type by type inference
     var location:any;
    
     //undefined and null could be assigned to any of the datatype
     var pincode:any=undefined;
     var state:any=null;
    
  3. Why the below is not possible in interface?
    I am having a interface and class like one below which results in compile time exception

    interface test1 {
    }
    
    class test2 implements test1
    {
        public foo;
    }
    
    let test: test1 = new test2();
    
    test.foo = 'test';
    

    The reason for the compilation error is when you reference a variable with specific interface in TypeScript, you can only use the properties and methods declared in the interface of the variable
    You are assigning test1 as a type of test variable, test1 interface doesn’t have foo property in it. so that’s why you are getting this error. If you change the type to let test: test2: new test2();. it won’t throw any error like one below

    let test: test2 = new test2();
    test.foo = 'test';
    

    There are two workaround for this. One is not to define the type while initializing variable like one below

    interface test1 { }
    class test2 implements test1{
        public foo;
    }
    let test = new test2();
    test.foo = 'test';
    

    Other is to use any while initializing variable

    interface test1 { }
    class test2 implements test1{
        public foo;
    }
    let test: test1 | any = new test2();
    test.foo = 'test';
    
  1. Services are mostly used in displaying datas from APIs
  2. To generate a new service use ng generate service Services/SERVICE_NAME
  3. services are injectable because they would be mostly called by other components
  4. Injection of services can happen at three level
    • AppModule – Same Instance of Service Injected would be available across application
    • AppComponent – Same Instance of Service Injected at this level would be available in this component and all child component
    • Any Other Component – Same Instance of Service Injected would be available to this component and child component(not to parent component)
  5. @Injectable is not needed if the Service is added in app.modules.ts

aboutus.component.ts

.
.
constructor(private objApi:ApiService) { 
    this.objApi.getDataFromRest();
  }
.
.

api.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  constructor() { }

  getDataFromRest()
  {
    return console.log("Data from Rest Method");
  }
}

If Else
aboutus.component.ts

export class AboutusComponent implements OnInit {
  showMsg: boolean = true;
  .
  .
  .
}

aboutus.component.html

<p *ngIf='showMsg; else elseBlock'>aboutus works from If block!</p>

<ng-template #elseBlock>
    <p>aboutus works from else block!</p>
</ng-template>

Output

aboutus works from If block!

Switch Case
aboutus.component.ts

export class AboutusComponent implements OnInit {
  .
  .
  color : string =  'pink';
  .
  .
}

aboutus.component.html

<div [ngSwitch] = 'color'>
    <p *ngSwitchCase="'blue'">Its Blue Color</p>
    <p *ngSwitchCase="'red'">Its Red Color</p>
    <p *ngSwitchCase="'green'">Its Green Color</p>    
    <p *ngSwitchDefault>Its Default Color</p>    
</div>

Output

Its Default Color

For Angular routing the routing option should have been enabled while starting new project.

  1. To define a link you need to use routerLink instead of href followed by route in other side of equals like one in app.component.html
      <ul>
        <li><a routerLink="/">Home</a></li>
        <li><a routerLink="/aboutus">About Us</a></li>
        <li><a routerLink="/services">Services</a></li>
        <li><a routerLink="/contactus">Contact Us</a></li>
      </ul>
    
  2. The list of routes needs to be defined in app-routing.module.ts. It is defined inside routes array list with path and component as key value pair like one below app-routing.module.ts
    const routes: Routes = [
      {path:'aboutus', component: AboutusComponent},
      {path:'services', component: ServicesComponent},
      {path:'contactus', component:ContactComponent}
    ];
    
  3. The path and one defined assigned to routerLink in html should be same. The component is the name of the component class which represent individual page of application
  4. If you are using absolute path then it would be /PATH which takes reference of component to be loaded form root url. If you are using relative path the it would be PATH (or) ../PATH (or) ../../PATH. Incase you are using relative path clicking the link of the same page from the page you are in should throw an error(Could not be verified)
  5. Navigating to link could be acheived by two ways
    • Using RouterLink in a tags
    • Using router navigate method in ts code
  6. routerLink always knows which route is currently loaded.router navigate method does not which route is presently loaded. So we always use activateRoute and pass relativeTo as parameter and pass relative URL as parameter

app-routing.module.ts

import { NgModule, Component } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import {AboutusComponent} from './aboutus/aboutus.component';
import {ServicesComponent} from './services/services.component';
import {ContactComponent} from './contact/contact.component';


const routes: Routes = [
  {path:'aboutus', component: AboutusComponent},
  {path:'services', component: ServicesComponent},
  {path:'contactus', component:ContactComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

app.component.html

<style>
ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
}

li {
  float: left;
}

li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

/* Change the link color to #111 (black) on hover */
li a:hover {
  background-color: #111;
}

.active {
  background-color: #4CAF50;
}

li {
  border-right: 1px solid #bbb;
}

li:last-child {
  border-right: none;
}
</style>
<div class="content" role="main">
  <ul>
    <li><a routerLink="/">Home</a></li>
    <li><a routerLink="/aboutus">About Us</a></li>
    <li><a routerLink="/services">Services</a></li>
    <li><a routerLink="/contactus">Contact Us</a></li>
  </ul>
</div>
<router-outlet></router-outlet>

sun security validator exception pkix path building failed
When it Happens
While doing maven build in intellij using maven tool bar. Not the build from intellij terminal which again calls command prompt

Why it Happens
Intellij has its own security store and java internally. So while doing build in case the security certificates are missing in inbuilt security keystore would result in the above error. Intellij java certificates are found in below location.Proxy certificates are not added to intellij keystore.

Fix

  1. The below should be done by running command prompt as administrator.
  2. Locate your network’s certificate: In a browser, navigate to “URL OF REPO” and then hit F12, go to certificates/security and get the top most certificate… Export it to MyCertificate.cer (base64 encoded)
  3. Navigate to security folder in intellij
    C:\Program Files\IntelliJ IDEA Community Edition 2019.3.4\jbr\lib\security
    
  4. Copy over MyCertificate.cer into the security folder
  5. Type “keytool -keystore cacerts -importcert -alias MyCertificate -file MyCertificate.cer” without quotes.
  6. Use the default password of “changeit”
  7. When prompted to trust the certificate type “yes”.Restart Intellij and try to run maven install again from maven to make sure the jars are imported

More Notes in above
We experienced this issue when a server changed their HTTPS SSL certificate, and our older version of Java did not recognize the root certificate authority (CA).

If you can access the HTTPS URL in your browser then it is possible to update Java to recognize the root CA.

In your browser, go to the HTTPS URL that Java could not access. Click on the HTTPS certificate chain (there is lock icon in the Internet Explorer, or the domain name left of the URL in firefox) and navigate the certificate hierarchy. At the top there should be a Primary Root CA. This could be missing from your java cacerts file. Note down the Issuer and Serial Number.

Type Script Command Line

//Install Typescript
>>npm install -g typescript

//Check version of Type Script
>>tsc -v

//Compile Typescript Code
//this would generate javascript file test.js
>>tsc test.ts

//Running js file
>>node test.js

Data Types in Typescript
Typescript allows to declare variable static(optional).If you use static typing then IDE will allow for type safety at compile time.

//Declaring String
let Name: String = "Mugil"; 

//Declaring Number
let Age: number = 25;

//Declaring Boolean
let Gender: boolean = true;

//Declaring Any datatype
let Street: any = 1 (or) "First" (or) true;

var is Function Scoped and let is block scoped
Using var

var foo = 123;
if (true) {
    var foo = 456;
}

console.log(foo); // 456

Using let

let foo = 123;
if (true) {
    let foo = 456;

}
console.log(foo); // 123
//Determined by Type Inference
var firstName = 'Mugil';
var age = 33;

//Determined by Annotation
var LastName: string = 'vannan';

//Not yet Determined 
var Location;

//Not yet Determined 
var Location;

var previousExp = 6 ;

//If you add a number and string it would be string irrespective of order
var totalExp = previousExp + "five";

//result in error
var Exp: number = previousExp + "five";

console.log("Total Exp - " + totalExp)

Interface

interface Person{
    name: String,
    age: number,
    pincode: any 
}

var objPerson:Person = {name: "Mugil", age:33, pincode:600018}

console.log(objPerson.pincode);

Class

class Person{
    private name: string;
    
    constructor(pname: string){
        this.name=pname;
    }    

    displayPerson(): void{
        console.log(this.name);
    }
}

var objPerson = new Person('Piggy');
objPerson.displayPerson();

Importing Namespaces and Modules

  1. Namespace are not widely used for development rather they are used internally. Modules are widely used for development
  2. In namespace you want to use would be imported using reference tag as in ArithmeticTester.ts, the one below. (Output is throwing error)
  3. When using modules the function would be directly added in module ts file as in Arithmetic.ts and referred using import in ArithmeticTester.ts
  4. Modules would be frequently used, the format would be import {FUNCTION_NAME} from ‘MODULENAME’

Namespace Example
Arithmetic.ts

namespace Arithmetic{
    export function Add(pNum1: number, pNum2: number){
        return pNum1+pNum2;
    }
}

ArithmeticTester.ts

/// <reference path="./Arithmetic.ts" />

let Sum = Arithmetic.Add(5,6);
console.log(Sum);

Modules Example
Arithmetic.ts

export function Add(pNum1: number, pNum2: number){
    return pNum1+pNum2;
}

ArithmeticTester.ts

import {Add} from './Arithmetic'

let Sum = Add(5,6);
console.log(Sum);

Output

11

Functions Example

  1. Arguments to function is optional. You can either set default value incase you are not sure about argument passed like in Add function
  2. You are still allowed to not pass any argument using ? in such case you would end up with different out put at runtime. NAN incase of number or undefined incase of string
  3. return type of function is not mandatory and its optional as in displayName function

Arithmetic.ts

//pNum2 would be considered as 0 incase only one argument is passed
function Add(pNum1: number, pNum2: number=0){
    return pNum1+pNum2;
}

function displayName(firstName: string, lastName? : string) : void{
    console.log("Her name is " + firstName + " "+ lastName); 
}
console.log(Add(5, 8));
console.log(Add(5));
displayName("Piggy");

Output

13
5
Her name is Piggy undefined

How to ensure type safety of arguments while using function
While defining function you may want to ensure the argument type passed.In such case you should declare the argument type the function accepts as one below.

In the below code you could see display name with two parameters(firstName and lastName). TypeSafety of second parameter is ensured by making it as string whereas first one could
be of anytype. If you try to pass something other than string as argument to second parameter then compiler would complain for error.

class SampleScript {
    displayName: (firstName, lastName: string) => void = function(firstName, lastName) {
        console.log("My Name is " + firstName + ' ' + lastName);
    }
}

window.onload = function () {
    var objSampleScript = new SampleScript();
    objSampleScript.displayName(101,'Vannan');
}

Output

My Name is 101 Vannan

Object Types
Object types could be function, module, class, interface and literal literals

Object Literals

 var square={h:10, width:10}
 var rectangle:Object ={h:10, width:20}

 //delcaring triangle as object literal
 var triangle:{};
 triangle={side1:10, side2:10, side3:10};

Functions as Object

var multiply = function (num: number) {
        return num * num;
};

//declaration of divide function object
var divide: Function;

divide = function (num1: number, num2: number) {
   return num1 / num2;
};

Object with variable and function

 var rectangle = {
        height:10,
        width:20,
        calculateArea: function() {
            return this.height* this.width;
        }
    };

    console.log(rectangle.calculateArea());
   var experience = {        
        sendExp: function (exp?: number) {
            if (exp < 3)
                return 'Beginner';
            else if (exp > 3 && exp < 6)
                return 'Intermediate';
            else
                return 'Fresher'; 

        }
    };

    console.log(experience.sendExp(5));
    console.log(experience.sendExp());

Output

Intermediate
Fresher

Function taking Object as parameter

var experience = {
        sendExp: function (job: { skill: String, exp?: number}) {
            if (job.exp < 3)
                return 'Beginner in ' + job.skill;
            else if (job.exp > 3 && job.exp < 6)
                return 'Intermediate in ' + job.skill;
            else
                return 'Fresher'; 

        }
    };

    console.log(experience.sendExp({ skill: 'Java' }));
    console.log(experience.sendExp({ skill: 'Java', exp: 5 }));

Output

Fresher
Intermediate in Java

Refinement
Purpose: Detail a Userstory into all that needs to be done to deliver its expected value
Time Spent 4 hrs for 2 week sprint(Includes planning)
Who Needs to attend Devops Team, PO
Optional Scrum Master

Qualities

  1. Open conversation to gather all info needed
  2. Shared Decision on task and planning
  3. Shared decision on estimation

Activities

  1. PO explains the why and what of the user stories
  2. Team defines how to build and deliver these stories
    • Identify prerequsites, dependencies and risks
    • Identify Tasks
    • Identify flow of task and planning
    • Change/Update the definition of done
  3. Team plays the planning Poker, estimates the relative amount of work in a user story

Outcome

  1. Identified Obstacles
  2. Detailed user stories that make the sprint plan
  3. Estimated user stories, ready for sprint planning

Planning
Purpose Define a sprint goal and make a plan to deliver it
Time Spent 4Hrs in 2 weeks sprint(Includes Refinement)
Who Needs to attend PO, Scrum Master, Team(Developers, Testers, Devops)
Optional NA

Qualities

  1. Commitment on sprint backlogs
  2. Clear priorities and sprint goal
  3. Shared knowledge about the sprint plan – how to deliver the stories and reach the goal

Activities

  1. Define what can be done next sprint
    • Product Owner and team set the sprint goal
    • Commit to capacity and velocity for next sprint
    • Devops team selects refined and estimated stories from the sprint backlog
  2. Define how it can be done
    • Finalize the plan to build the stories and deliver the sprint goal
    • Assign stories/tasks
    • If needed adjust the sprint backlog
    • Commit to the sprint backlog and start

Outcome

  1. Shared decision on tasks and planning
  2. Sprint goal, Sprint plan and Sprint backlog

Standup
Purpose Align activities and plan the upcoming day
Time Spent 15 min/day
Who Needs to attend Devops Team, Scrum Master
Optional PO

Qualities

  1. Focus on sprint goal
  2. Enhanced communication and collabration
  3. Fast Decision making
  4. Identified obstacles and impediments

Activities

  1. Team reports progress to each other(not to scrum master) by answering 3 questions per person
    • What did you finish yesterday?
    • What will you work on today?
    • What obstacles are in your way and do you have a help question for the team?
  2. Measuring progress towards deliverable’s
  3. Define the impediments that are outside our team’s influence and ask scrum master to help, solve and escalate those.

Outcome

  1. Updated Scrum board
  2. Updated impediment List

Review
Purpose Inspect the delivered value/items in last sprint and adapt the backlog with feedback from stakeholders
Time Spent 2 hrs for 2 week sprint
Who Needs to attend Devops team, Product owner, Scrummaster, Stakeholders
Optional NA

Qualities

  1. Focus on delivered value
  2. Done is Done(or not)
  3. Open conversation about work delivered and expectations
  4. Updated Backlog

Activities

  1. Devops team shows work being done
  2. Devops team tells how they managed difficulties
  3. Stakeholders ask questions and give feedback
  4. Productowner accepts work being done or pushes back to backlog
  5. Product owner updates and re-prioritizes the backlog
  6. Scrummaster and team share common understanding of last metrics(Burndown, velocity and happiness)

Outcome

  1. Updated Metrics
  2. Updated backlog
  3. Closed Sprint

Retrospective
Purpose Inspect what went well during sprint and adapt what can be improved
Time Spent 1.5 hrs for 2 week sprint
Who Needs to attend Team, Scrum master(Mandatory)
Optional PO

Qualities

  1. Open dialogue and all voices to be hear
  2. Focus on continuous improvement
  3. Collects facts and generate insights
  4. Move forward

Activities

  1. Set the context for safety – Share purpose and structure of the meeting
  2. Evaluate the last agreements and actions taken
  3. Gather new input on what went well and what to improve
  4. Prioritize improvements
  5. Detail the top 3 actions for next sprint

Outcome

  1. Maximum 3 actionable improvements for new sprint

Frequently Asked Questions

  1. What are basic things to be taken into consideration while taking a story for refinement (or) how you will consider a story to be Ready for refinement (or) Refinement DOR
    1. The priority of story should have been decided
    2. Supporting documents(Use case documents and confluence) for the story should be available
    3. Requirement and scope of the story should have been well defined
    4. Walk through should have been done by business analyst or product owner stating how the changed version of software product should behave and look like.
    5. Dependencies with other team would have been sorted
    6. Implementation and timeline details should be well defined
  2. What are basic things to be taken into consideration when you tell a story is done with refinement (or) (or) Refinement DOD
    1. Checklist of things that needs to be done should be added
    2. The story should have been pokered(1,2,3,5,8)
    3. All the details of the story should be clearly listed
    4. Subtask should have been created
    5. Testcase design document should be ready
    6. Dependencies and impact on devOps should have been discussed
    7. Acceptance Criteria should have been listed