TypeScript Mastery: The Ultimate Guide to Building Robust JavaScript Applications
Table of contents
- 1>why do we need “TypeScript” when we have “JavaScript”?
- a> Installation of “TypeScript” :→
- 2> Now we have to move on to 2nd part that’s compile “TypeScript”
- 3> How “TypeScript” code will run after compilation?
- a>without making the folder structure.
- b>with folder structure.
- 4>how to make the tsconfig. part in “TypeScript?
- 5>how to watch “ts” changes in the project ?
- 6>why we need “TypeScript” ?
- 7> Is TypeScript new language ?
- let’s deep dive into “TypeScript”:→
- 1>primitive data-type:→
- 2>Array:→
- 3>Tuples:→
- 4>E-num (e-numeration):→
- 5>Any ,Unknown ,Void, null ,undefined, never :→
- 6>Type inference and Type annotation :→
- Type inference:→
- Type annotation :→
- 7> Type interfaces and type alias :→
- 8>Class and object (in ts):→
Description:→ Unlock the power of TypeScript with our comprehensive guide. Learn how to enhance your JavaScript development, improve code quality, and build scalable applications with strong type checking and modern web development techniques.
1>why do we need “TypeScript” when we have “JavaScript”?
So, the answer we will in after sometimes firstly we will install the “TypeScript” in our system and then we will answer this. So, it will be a fun journey so let’s start :→
a> Installation of “TypeScript” :→
so there is couple of way we can do this :→
i>click on this to install "TypeScript"
or
npm i -g typescript
use this command on the “vs code” terminal. And congratulation! TypeScript is in your system. To check that you have to write
tsc -v
by which we can get the version of the “TypeScript”. And if it’s showing then …. yess yesss yessss!!!… installation is done . :-)
2> Now we have to move on to 2nd part that’s compile “TypeScript”
For that we have to write another command that we also have to execute on “terminal” .
tsc
“tsc” is the only compiler that will help to compile the “TypeScript” code to “JavaScript” . And that will be again “byte code” means all “0” and “1”.
3> How “TypeScript” code will run after compilation?
so there 2 analogy to use “TypeScript”
a>without making the folder structure.
i> write your “ts” code.
ii> compile it to “js”.
iii>make a html file attach the the “js” code .
iv> and see the out put on console section in the inspect part of broswer.
b>with folder structure.
there process will be same but here we have to mention the outdir(output location)[js part] and rootdir(input section)[ts part] in “tsconfig section”.
now here come the next question “ how to make the tsconfig part?” so let’s answer it too.
4>how to make the tsconfig. part in “TypeScript?
tsc -init
this will generate tsconfig where we can set-up the “rootdir” and”outdir”.If we want to write the the adress we can make sure the input and output part of the “project”.Now the question is every time we make any change in “ts” file we have to restart the “ts” with “tsc” again and again. we will answer it in this section.
5>how to watch “ts” changes in the project ?
tsc -w
we have to use in “terminal” in “vs code” and that’s enough. if we change anything in “ts”, we will the changes in “js” file and console(browser) too.
now the question is when we have “JavaScript” then why we are trying to go through the “new language” named “TypeScript”. here is why →
6>why we need “TypeScript” ?
i>”JavaScript” is dynamically typed language. “TypeScript” Statically typed language.
note :→ now the question is :→ what is “Dynamically typed language” and “Statically typed language” ?
“Statically typed language**” means it checks the “types” of variable during the compilation of code.**
“Dynamically typed language” means it checks during the “run-time” that’s the “execution of the code”.
ii>”JavaScript” is interpreted language and “TypeScript” is compiled language.
note :→ now the question is :→ what is “compiled language” and “interpreted language” ?
“compiled language” means it get complied to machine code then execute on the computer.
“interpreted language” means it will be get compiled as it runs(line by line as execute)
that the theoretical reason of we should use “TypeScript”.
now let’s under stand this by code.
here we will write the same code see the benifits of it .
let a=20;// started as number
a="ayush";// changed to string
console.log(a);// ayush
here a is “number” at first and then a became “string” this can make error in the program . let’s asuume in “auth” project we wanna take username only as “string”. when we specific type we us this.
let a = 20; // started as number
a="ayush"
console.log(a); // error
this same code will give us error!!!.. let’s see that too.
here as this picture we have shown the “Error” we try to use a as “number” and later try to make “string” but “ts“ will nit do it. And also give me the error. here is the right code
let a :number = 20; // started as number
console.log(a); // 20
here the js file after compilation it’s like this code :→
"use strict";
let a = 20; // started as number
console.log(a); // 20
so. i guess in was the enough motivation to start our journey with TypeScript the another main reason is it give us error while writing the code not in the run_time stage as it’s not a “interpreted language” as “JavaScript” so it make more robust system and more efficient all in all.
7> Is TypeScript new language ?
short answer : NO
long answer : TypeScript is superset of “JavaScript” . It has some extra properties that make the “js” code more better and robust and on this section we are gonna see those features.
let’s deep dive into “TypeScript”:→
1>introduction to basic types: →
so there is 2 type of data type in the "programming” part.
a> primitive data-type :→ number, string , boolean.
b>no-primitive data-type :→ array, object etc.
now here is the question is :→ what’s primitive data-type and non-primitive or reference data-type ?
primitive is data-type that
1> cannot be broken further and represent a simple data-type.
2>And has a fixed type too.
3\> **primitive data-type is “addressed by value” means if we copy the variable in another variable .It give actual copy of the variable(**separate copy), it give us the actual value of the variable , js/ts store the primitive data type in “call stack”. And if we changes the copied variable (another one). then only the copied variable will be changed. But the original value will be unchanged.
let original_num:number=12;
let copied_num:number=original_num;
copied_num=13;
console.log(`copied_num is ${copied_num} and original_num is ${original_num}`);
// adress by value
example:→number ,string ,boolean etc.
reference / non-primitive is data-type that
1> can be broken further cz it’s mixture of one or many data-types.
example : object ,arrays etc.
let course_obj={
first_name:"piyush",//string
age:12,// number
is_paid:true // boolean
}
2>non-primitive data-type is “addressed by address” means if we copy the variable in another variable .it doesn’t give actual (separate)copy of the variable , it give the address of the variable to us, js/ts store the non-primitive data type in “heap memory” . And if we changes the copied variable (another one). then only the copied variable will be changed. And the original var will be also changed.
1>primitive data-type:→
data-types are :→
a>number
b>string
3>boolean
2>Array:→
as normal “js” but “ts” define the type as we assign the values of “array”.
let ayush = [1, 2, "ayush", true];
console.log(ayush);
let piyush = [1, 22, 3];
console.log(piyush);
3>Tuples:→
A tuple is a typed array with pre-defined length and types for each index.
let ayush: [string, number] = ["batman", 22];
let piyush: [string, number] = ["ironman", 23];
//tuple
4>E-num (e-numeration):→
An e-num is a special "class" that represents a group of constants (unchangeable variables).
enum StatusCodes {
NotFound = 404,
Success = 200,
Accepted = 202,
BadRequest = 400
}
console.log(StatusCodes.NotFound);
console.log(StatusCodes.Success);
5>Any ,Unknown ,Void, null ,undefined, never :→
a>any:→
“Any” :→if we don’t specify the type of the variable in my program then it will automatically set the value to any. Then we can assign any value to the variable that’s means if we use “any” keyword then it will just “turn off” …. “TypeScript”.. cz we can do the same task with “JavaScript”.
let ayush;
ayush = 12;
ayush = "batman";
if we don’t mention any type then by default variable’s type will be “any”.
note:→don’t use “any” keyword if u wanna use “TypeScript”.
b>unknow:→
let ayush: unknown;
ayush = 12;
ayush = "batman";
if (typeof ayush === "string") {
console.log(ayush.toUpperCase);
}
difference between “any” and “unknow” is later we can assign the value to it. and use it by checking the type.
c>void:→
if a function doesnot return any thing, we have to use “void” keyword another wise we have to specify the return type of the function.
function ayush(a: number): void {
console.log((a = a + 10));
}
let piyush = ayush(10);
if the function is returning anything then we have to mention it’s type like:→
function ayush(a: number): number {
return((a = a + 10));
}
let piyush = ayush(10);
console.log(piyush);
At that point we have to use “return keyword”. otherwise we will get error.
now the question is :→ why “void” function is being used?
the reason is :→ it is used to “console.log” , “modifying the states” , “triggering the async function”.
d>null :→
let’s assume we are trying to find a name in database of millions. And if we can’t find then simply we will get “null” as result. that means we can’t further add or assign the value in the variable.
e>undefined :→
let a: undefined;
f>never :→
function ayush(): never {
while (true) {}
}
ayush();
while(true) => will just start infinite loop. and if run then the programm will not stop if we want our program or function doesn’t show anything. We will use “never” keyword.
6>Type inference and Type annotation :→
let a=12;
Type inference:→
if we write the above code and “typescript” auto-matically detect that a is “number”. that’s called as “Type inference”.
Type annotation :→
let b: number;
b = 13;
when we mention the “type” of the variable on our own that’s “Type annotation”.
7> Type interfaces and type alias :→
interface MOmo {
name: string;
password: string;
age: number;
}
function ayush(abcd: MOmo) {
return `${abcd.name} is ${abcd.age}years old and his password is : ${abcd.password}`;
}
let batman = ayush({ name: "ayush", password: "ayush123", age: 12 });
console.log(batman);
interface is a syntactical contract that defines the structure and properties of the “object”.
see the error for better understanding.
a>extending interfaces :→
using “extends” keyword we can add more “property” by which we can add more properties to a particular object i.e. “MOmo2” .
in the functional parameter we are passing adcd1 that has same property as “MOmo2“ and that’s what interface and extending interfaces do.
interface MOmo1 {
name: string;
password: string;
age: number;
}
interface MOmo2 extends MOmo1{
isEating: boolean;
}
function piyush(abcd1: MOmo2) {
return `${abcd1.name} is ${abcd1.age}years old and his password is : ${abcd1.password} and "${abcd1.isEating}" means you are having momo`;
}
let catwoman = piyush({ name: "piyush", password: "piyush123", age: 18, isEating:true});
console.log(catwoman);
here is the error part to understand it more better.
b> Type Alias :→
it is used to make custom “types” in the language.
type numbor = string | number;
let password: numbor = "ayush";
password = 123;
console.log(password);
c>intersection of “types” :→
type User = {
name: string;
password: number;
};
type admin = User & {
getdetails: boolean;
};
function Ayussh(batman: admin) {
return `${batman.name} have a password is: ${batman.password} and if ${batman.getdetails}is true then you are eating momo`;
}
let piyush = Ayussh({ name: "Batman", password: 123, getdetails: true });
console.log(piyush);
here with a “&“ sign we can do “intersection of types” and here admin type is a great example of it. Intersection is used to extended the types.
8>Class and object (in ts):→
a>Making the Class :→
class User {
name = "ayush";
age = 18;
isfat = true;
}
let newUser1 = new User();
here you can see the output.
b>Constructors :→
Class constructors are very similar to functions. In this class the we don’t have function use “Constructors function”.
example:→ the car factory there is many machine that make car, here the car machine is the “Constructors Function” .If we make class without
class User {
constructor(public name: string, public age: number, public isFat: boolean) {}
}
let ayush = new User("ayush", 18, true);
let piyush = new User("piyush", 19, false);
output:→