Introduction
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
- let message='Hello Guys';
- 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:
- var message = 'Hello Guys';
- 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
Note
TypeScript not allowing special characters in the message like let’s but only lets.
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.
Boolean, Number and String are the types used in TS
- export {}
- let isBeginner: boolean = true;
- let total: number = 0;
- let name: string = 'Bharat';
- let sentence: string = `My name is ${name}
-
- I am a beginner in TypeScript`;
- 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,
- let isnew: boolean = null;
- let myname: string= undefined;
An Array type can be declared in 2 Syntaxes,
- let list1: number[] = [1, 2, 3];
- let list2: Array < number > = [1, 2, 3];
-
- let person1: [string, number] = ['Bharat', 31];
Enum Type is a concept of declaring friendly names to a set of numeric values
- enum Color {
- Red = 100, Blue, Green
- };
- let r: Color = Color.Red;
- let b: Color = Color.Blue;
- let g: Color = Color.Green;
-
- console.log(r);
- console.log(b);
- 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:
- let b=10;
- 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.
Functions
- function add(num1: number, num2: number) {
- return num1 + num2;
- }
- add(5, 10);
- 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.
- function add(num1: number, num2: number = 10) {
- return num1 + num2;
- }
- let b = add(5, 20);
- let c = add(5);
- console.log(b);
- 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.
Interfaces
- export {}
-
- function fullName(person: {
- firstName: string,
- lastName: string
- }) {
- console.log(`${person.firstName} ${person.lastName}`);
- }
- let p = {
- firstName: 'Bharat',
- lastName: 'Bhushan'
- };
- 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.
- export {}
- interface Person {
- firstName: string;
- middleName ? : string;
- lastName: string;
- }
-
- function fullName(person: Person) {
- console.log(`${person.firstName} ${person.middleName} ${person.lastName}`);
- }
- let p = {
- firstName: 'Bharat',
- lastName: 'Bhushan',
- middleName: 'Veera'
- };
- 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.
- class Employee {
- employeeName: string;
- constructor(name: string) {
- this.employeeName = name;
- }
- greet() {
- console.log(`Good Morning ${this.employeeName}`);
- }
- }
- let emp1 = new Employee('Bharat');
- console.log(emp1.employeeName);
- 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
- class Employee {
- employeeName: string;
- constructor(name: string) {
- this.employeeName = name;
- }
- greet() {
- console.log(`Good Morning ${this.employeeName}`);
- }
- }
- let emp1 = new Employee('Bharat');
- console.log(emp1.employeeName);
- emp1.greet();
- class Manager extends Employee {
- constructor(managerName: string) {
- super(managerName);
- }
- delegateWork() {
- console.log(`Manager Delgating Tasks`);
- }
- }
- let m1 = new Manager('Julie');
- m1.delegateWork();
- m1.greet();
- 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!