Typescript Quick Learning Tutorial Blog - Part One


Hi guys, let’s have a Quick TypeScript tutorial by going through my blog.

What is TypeScript and Why Use It? 

It’s an Open Source Programming Language developed & maintained by Microsoft.
Typed super set of JavaScript.
Compiles down to plain JavaScript.
Superior to Dart and Coffeescript languages. It can be easily renamed to .js and works fine.
Optional static typing and type inference.
Adds Type support to JS. Easy error detection in the beginning.
Auto-intellisense prompts you while programming.
Enhanced IDE support.
Rapid growth and use.
Main programming language of Angular and React JS.
Development Environment Setting up
Download and Install Nodejs
Node -v
See the version
Install Typescript globally
Npm install -g typescript
See the version by typing tsc -v
Download and install Visual Studio code from code.visualstudio.com
Create a new path TypeScript folder and enter into it using Nodejs prompt.
Give code . and access into the Visual Studio code editor for your further development activities.
Create a new file main.ts
  1. let message='Hello Guys';  
  2. console.log(message);  
Open PowerShell command explorer
Run the command: tsc main.ts
The above command creates a new file main.js in the Left Navigation Files. Section: main.js which has the below program code:
  1. var message = 'Hello Guys';  
  2. console.log(message);  
Now run the command: node main.js
We have some error in the .TS file. To solve it we need to add an Export/Import command in order to consider it as a module but not a script command.
After Re-Compiling [using same command tsc main.ts] the Error disappears and gets reflected accordingly on the main.js file too.
Run another command: tsc main –watch
Make some changes on your main.ts file
Open another PowerShell Terminal and run: node main
You can see the changed message
TypeScript not allowing special characters in the message like let’s but only lets.
Variable Declarations
Unlike Traditional js, Typescript encourages let and const keywords[support Block level scoping].
How scope and word declarations can trick you in javascript while in TS we have Block scope additional to JS has Global and functional scope
Differences between let and const
Let can be declared without Variable Initialization while const must be declared with a Variable Initialization.
For example, we can have declarations like
Let sum;
Const title; is not allowed as it’s required Initialization and should be constant always!
The above 2 concepts reduced the number of errors in TS programming.
Variable Types
Boolean, Number and String are the types used in TS
  1. export {}  
  2. let isBeginner: boolean = true;  
  3. let total: number = 0;  
  4. let name: string = 'Bharat';  
  5. let sentence: string = `My name is ${name}  
  7. I am a beginner in TypeScript`;  
  8. console.log(sentence);  
Now go to the PS Terminal and run the PS commands,
tsc main.ts
#To create an equivalent main.js file
Node main
You can see the output below:
Null and undefined are classified as subtypes of all other types. It means we can assign the values to them to above Variable Types.
For Ex,
  1. let isnew: boolean = null;  
  2. let myname: string= undefined;  
An Array type can be declared in 2 Syntaxes,
  1. let list1: number[] = [1, 2, 3];  
  2. let list2: Array < number > = [1, 2, 3];  
  3. // Combination of values in the Array  
  4. let person1: [string, number] = ['Bharat', 31];  
Enum Type is a concept of declaring friendly names to a set of numeric values
  1. enum Color {  
  2.     Red = 100, Blue, Green  
  3. };  
  4. let r: Color = Color.Red;  
  5. let b: Color = Color.Blue;  
  6. let g: Color = Color.Green;  
  7. //above list starts numbered from 0,1,2 You can do manual assigning too just as above  
  8. console.log(r);  
  9. console.log(b);  
  10. console.log(g);  
You will get the Out put 100,101,102 as index starts from 100 as manually declared above.
If we are unsure about some dynamic value just declare it with any type.
With any type of variable, we can undergo number of errors, like calling it as a function, trying to convert it into Uppercase, console.log with different variable type value, etc. This gives us lots of confusion. TS doesn’t throw Errors.
To tackle this issue TS3.0 has introduced another variable type unknown.
Type Inference is something making the TS self understand the variable value without explicitly declaring it.
For example:
  1. let b=10;  
  2. let b: string ='bharat';  
For the 2nd time, the TS threw an error, as it has already taken variable b type as a number and can’t accept again it as a string type for which we try to come up with a new concept called MultiType or Union Type concept.
The multitype declaration accepts multiple variable type declarations except for String type, whereas any type of declaration accepts String type as well.
Multitype (also called Union Type) is also supported with Intellisense, while anyType is not supported.
  1. function add(num1: number, num2: number) {  
  2.     return num1 + num2;  
  3. }  
  4. add(5, 10);  
  5. add(5, '10');  
For the 2nd time TS threw an error as the above add function only accepts number type as the inputs.
In the above example, return type has been understood to be number type without declaring it additionally in the TS script.
Let’s discuss Optional, Required and Default Parameters in the Functions Topic.
We can have as many as Optional Parameters which are defined with a? [Ex:- num2?] but should be surely declared after the Required Parameters in the Function definition.
Default Parameters are basically optional parameters with a set value instead of undefined.
  1. function add(num1: number, num2: number = 10) {  
  2.     return num1 + num2;  
  3. }  
  4. let b = add(5, 20);  
  5. let c = add(5);  
  6. console.log(b);  
  7. console.log(c);  
The above example has num2 has default value declared as 10 and will be used if not declared in your parameters passing while using the add function. Hence, the result for printing c is 15.
If both parameter values declared separately as in the first case the above default value gets overwritten and gives you the result as 25.
  1. export {}  
  3. function fullName(person: {  
  4.     firstName: string,  
  5.     lastName: string  
  6. }) {  
  7.     console.log(`${person.firstName} ${person.lastName}`);  
  8. }  
  9. let p = {  
  10.     firstName: 'Bharat',  
  11.     lastName: 'Bhushan'  
  12. };  
  13. fullName(p);  
The above function gives the result: Bharat Bhushan as person object has 2 properties: firstName and lastName. TS simply prints the variable p that has both properties assigned.
But now imagine if it has more properties to an object of the function.
Interface can be defined and passed into the function to handle more properties of a given object for a smarter code development.
  1. export {}  
  2. interface Person {  
  3.     firstName: string;  
  4.     middleName ? : string;  
  5.     lastName: string;  
  6. }  
  8. function fullName(person: Person) {  
  9.     console.log(`${person.firstName} ${person.middleName} ${person.lastName}`);  
  10. }  
  11. let p = {  
  12.     firstName: 'Bharat',  
  13.     lastName: 'Bhushan',  
  14.     middleName: 'Veera'  
  15. };  
  16. fullName(p);  
Here the Output is: Bharat Veera Bhushan
We have explored the usage of Interface along with the Function usage in TS.
Class and Access Modifiers
Class is a collection of Functions, Interfaces, Variables, Objects, etc.
  1. class Employee {  
  2.     employeeName: string;  
  3.     constructor(name: string) {  
  4.         this.employeeName = name;  
  5.     }  
  6.     greet() {  
  7.         console.log(`Good Morning ${this.employeeName}`);  
  8.     }  
  9. }  
  10. let emp1 = new Employee('Bharat');  
  11. console.log(emp1.employeeName);  
  12. emp1.greet();  
The above example helps me to greet with the employee name.
That’s the basic idea of a Class nothing different from C# or Java.
Because of Classes we have Class based Inheritance possible. It can be used for Class Properties inheritance and established using a simple keyword called: extends
Here is a cool TS program explaining Inheritance
  1. class Employee {  
  2.     employeeName: string;  
  3.     constructor(name: string) {  
  4.         this.employeeName = name;  
  5.     }  
  6.     greet() {  
  7.         console.log(`Good Morning ${this.employeeName}`);  
  8.     }  
  9. }  
  10. let emp1 = new Employee('Bharat');  
  11. console.log(emp1.employeeName);  
  12. emp1.greet();  
  13. class Manager extends Employee {  
  14.     constructor(managerName: string) {  
  15.         super(managerName);  
  16.     }  
  17.     delegateWork() {  
  18.         console.log(`Manager Delgating Tasks`);  
  19.     }  
  20. }  
  21. let m1 = new Manager('Julie');  
  22. m1.delegateWork();  
  23. m1.greet();  
  24. console.log(m1.employeeName);  
Access Modifiers are basically key words that set the accessibility of properties and methods of a Class.
By default, all the class members are public freely accessible throughout the program.
When Class member is set to private, it can’t be accessible externally outside a Class. This is a way to secure the Class properties.
When Class member is set to protected, it can’t be accessible outside the Base Class, and the Derived Class is implementing the Class properties to be protected.
Stay Tuned for more Content. Sharing is Caring..Typescripting will help you to rock in Developing!