Typescript Quick Notes for Angular Developers

Typescript Quick Notes for Angular Developers:

As because of angular’s reach angular developers are forced to learn typescript. It is not tough but it is better to know the below basic syntax to code faster.

 

1. Converting array to JSON in typescript

 


selectedItems = [];

JSON.stringify(this.selectedItems);

 

 

 

2. For loop in typescript

 


for(let item of items){

console.log(item.itemName)

}

 

items is an array/collection of item.

 

 

3. String concatenation in typescript

 


appendTxtTemp:string = 'Hello';

this.appendTxtTemp = this.appendTxtTemp.concat(" ") .concat('World');

// prints Hello World

 

 

4. Single quote or Double quote in typescript?

 

Like in javascript / jQuery in typescript also we can surround string with single quotes or double quotes.

 

There is no particular standard to follow, but it is advisable to use double quotes to surround string. If you are using JSON, then very good to go with double quotes only.

 

We have few other advantages with double quotes:

  • JSON notation is written with double quotes.
  • Double quotes mean a string in many other languages. [i.e java]
  • Double quotes eliminate the need to escape apostrophes.

[“I’m good” and ‘I\m’ good’]

 

 

5. Converting object to json in template file

You can use the json available pipe in your angular template file

<td>{{coupon.categoryList | json}}</td>

 

 

6. Empty or not empty check in typescript

We don’t have any empty methods in typescript, but we can directly check like this,


if(coupon.categoryList){
// if categoryList not empty only it will come here.
}

 

7. To add (push) values to array in typescript

 


tempUserDuplicateArray:any=[];

this.tempUserDuplicateArray.push("Rithvik");

 

8. To check whether array contains (or) includes the values already


tempUserDuplicateArray:any=[];

this.tempUserDuplicateArray.push("Rithvik");

if(!this.tempUserDuplicateArray.includes("Rithvik")){

// come inside only when the array does not contain "Rithvik"

}

This logic can be used to add only unique values to the array in typescript.

9. Trim function in typescript


tempString:string = ' God ';

console.log(tempString); // prints  God

console.log(tempString.trim()); // prints God

I could not visualize the output clearly here, trim basically removes white spaces in both head and tail from the string.

 

This post will be updated regularly with new typescript question/tips and useful things to help angular kings.

 

You can share your notes on this to help someone like you!

230 total views, 1 views today

Leave a Reply

Your email address will not be published. Required fields are marked *