README
Basic Types Of Typescript
GitHub Link: Module-1
Are you ready to dive into the world of TypeScript? 🔥
This module introduces the power of TypeScript, a supercharged version of JavaScript that helps you write cleaner, more reliable code. Here's a sneak peek at what you will learn:
-
Intro to the TypeScript Technocrat Mission: We'll kick things off by introducing TypeScript and explaining how it empowers you to become a web development "Technocrat"—someone who builds robust and efficient web applications.
-
Introduction to TypeScript: You'll learn what TypeScript is, why we use it, the benefits of using TypeScript, and how it builds upon your existing JavaScript knowledge.
-
Install typescript and node version manager: We'll guide you through setting up the necessary tools, including how to install TypeScript and introduce you to Node Version Manager.
-
Your First TypeScript Program: Then the exciting part begins! You'll write your first TypeScript program!
-
Mastering Basic Data Types: TypeScript helps you manage different types of data. You'll learn about numbers, strings, Booleans, and other data types that make your code more organized.
-
Object Power, Optional and Literal Types: Explore the world of objects in TypeScript—how to structure them, define optional properties, and even use literal types for greater control.
-
Function in TypeScript: Functions are the building blocks of any program. We'll teach you how to write functions in TypeScript! You'll learn about features like parameter typing and return type definition.
-
Destructuring in TypeScript: Simplify working with complex objects using destructuring—a powerful technique that allows you to extract specific data with ease.
-
Type Aliases in TypeScript: Learn how to create type aliases, which are like nicknames for complex types. This will make your code cleaner, more readable, and easier to maintain.
-
Union and Intersection Types: Imagine being able to define variables that can hold different types of data. That's the power of union and intersection types in TypeScript!
-
Ternary, Optional Chaining & Nullish Coalescing: Discover special operators like ternary operators, optional chaining, and nullish coalescing. These operators make your code more concise and safer to work with.
-
Unveiling Never, Unknown & Nullable Types: TypeScript offers advanced type concepts like "never," "unknown," and nullable types. These advanced concepts give you more flexibility when dealing with unexpected or nullable values.
By conquering these topics, you'll be well on your way to becoming a TypeScript whiz and crafting superior web applications! 💥
1-0 Intro To Typescript Technocrat Mission

1-1 Introduction To Typescript
What is Typescript?
- Typescript Is An Object Oriented Programming Language That Is Built On Top Of Javascript With Extra Features.
- Typescript is extended version of javascript loaded with extra features
Why Typescript?
- Problem of Javascript
- Dynamically Typed Language, For this reason we can declare any kind of variable any time, this is a problem, In small scale project we may catch but in large scale project we cant check the type checking error so easily.
- In js if we do not go in run time we are not able to catch the error in run time
- Js do not support object oriented by default, we use syntactic sugar

- When the situation is like we need to work on a project that should be supported in older version browser, in this situation typescript helps us to choose in which version of js we want to work. Since at the end of the day typescript is converted in javascript and Typescript can be transpiled into older versions o0f javascript

Can Browser Recognize Typescript?
- Browser can not run typescript code, at the end of the day we need to transpile Typescript code to javascript code and the js code is run by browser/ node.js
Benefits Of Typescript?
- Supports older Browser
- Type safety ( we can not declare any type of variable any time this solves the problems of dynamically typed problems of js )
- Js Types in Ts
- Number
- String
- Boolean
- Null
- Undefined
- Object
- Symbol
- Ts has its own types including the js types
- Interface
- Void
- Array
- Tuple
- Enum
- Union
- Intersection

- Increases Productivity (if we declare any utility function and import any other file we do not need to go to the file and check what types we have to use or what parameter we have to send )
- Less Bug and Less Testing
Drawbacks Of Typescript?
- Type Complexity : Even its a simple code still we need to declare type
- Limited Library Support : Some libraries do not support typescript
- Over Engineering
- Migration Challenge in converting js to ts
1-2 Installation Of Typescript and Fast Node Version Manager
- We need to install node version manager since ts will be converted to js and to run the js in server side we need a run time, we will use node.js as the run time
Install Node.js
- Node.js Installation using command line since it will give us flexibilities switch in different version
- write "winget install Schniz.fnm" this command in powershell, this will Download and install fnm
- "fnm install 22" write this command to install version 22
- "fmn list" this command will show the list of node versions that are provided by fnm
- "fnm env --use-on-cd | Out-String | Invoke-Expression" use this command to set the environment
- "fnm install 22.15.0" this command to install required version
- "fnm use 22.11.0" to switch version
Install Typescript
- Go to cmd and "npm install -g typescript" . We Are Installing it globally
- To check the version "tsc -v" . Tsc Is a Typescript Compiler which converts ts code to js code
1-3 Write Your First Typescript Program
- index.ts
let course = "Next Level Web Development";
console.log(course);
-
even if its ts file it will show output if we run "node index.ts" since we have used nothing of ts here
-
index.ts
let course: string = "Next Level Web Development";
console.log(course);
-
This will show error that node.js can not run the ts code directly
-
We need typescript compiler. "tsc index.ts". this will transpile the ts code to js code
-
In the folder structure is module1--> src --> index.ts write this command to transpile to js "tsc .\module1\src\index.ts"
-
if we open ts and the transpiled js file in same folder and opened it will show an error so we will keep the transpiled files in another folder.
-
we need a typescript configuration file fo this we have to write "tsc --init", it will give us tsconfig.json file
-
tsconfig.json configuration
"target": "ES5" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// will find out root dir and set the directory where the ts file is
"rootDir": "./module1/src/",
// we will find out outDir and set this to tell where the transpiled js code will be stored
"outDir": "./module1/dist"
- After configuration we will just have to write "tsc" to transpile the files to js. we do not need to say the specific file names and folder."tsc" command will convert all the ts files in the folder in src and keep it in dist folder"
1-4 Basic Data Types Of Typescript

Primitive data Types
- Number
- String
- Boolean
- Null
- Undefined
- symbol
Non-Primitive data Types
- In js we just use object in non-primitive since we know array is also a object and object is a object type data.
- But Typescript has gave us specific Array and Object Type data Type.
- Array
- Tuple
- Object
- We will not get the ts data types in run time, we will compile ts to js and use node.js to to run the js
- So? how does ts helps us? It Helps us when we compile the code it will show us the errors related to the types.
Starting With Primitive Data Types
-
1.4.ts
-
Typescript is smart . Even If We Have not gave any type it will infer the data type from our value.
-
This is called typescript implicit data types
// String
let firstName = "Sazid";
- we can also tell the data type explicitly
let lastName: string = "Sazid";
- Number, Boolean, Null, Undefined Data Types
// Number
let roll: number = 123;
// Boolean
let isAdmin: boolean = true;
// undefined
let x: undefined = undefined;
// Null
let y: null = null;
- If we do not declare and do not assign any value the typescript will infer as any type
- We can keep any type of data ts will not mind
let d;
d = "Sazid";
d = true;
-
Basically we should not use any type, if wer use this we will not get the facilities of ts
-
We Should Declare Like this
let p: number;
// p = "123" not assignable
Starting With Non-Primitive Data Types
- Array Types
- Here as well ts will infer that its an array
let friends = ["rachel", "monica"];
- We can explicitly define the types
let friends: string[] = ["rachel", "monica"];
let eligibleRoleList: number[] = [1, 2, 3, 4, 5];
- If we want to push different type of variable it will show error
let friends: string[] = ["rachel", "monica"];
friends.push(2); // will show error
- Tuple type (Tuple can be in pairs like 2,3,4 or any numbers of pairs)
- Tuple is also a special kind of array in which orders are maintained of type of values and the number of values
- Tuple --> array --> order --> type of values
let coordinates: [number, number] = [1, 2];
- What is the facility of Tuple ?
- Without Tuple
let ageName = [50, "Mr.Sazid"];
// if we want we can chang the value by grabbing the index and add another value in the array as well
ageName[0] = "Mr.Sazid";
// this is not right
- Using Tuple
let ageName: [number, string, boolean] = [50, "Mr.Sazid", true];
// ageName[0] = "Mr.Sazid";
// now we cant
1-5 Object, Optional and Literal Types
- Object is an important data structure of object.
- Implicit Types
// Reference Type --> Object
// this is implicit type, this will automatically infer the types
const user = {
firstName: "Sazid",
middleName: "Abedin",
lastName: "Persian",
};
- If we want Explicit Types
// explicit and optional type
const user: {
company: string;
firstName: string;
// this is for making optional(It maybe string | Undefined ) and which is not made optional is taken as required
middleName?: string;
lastName: string;
isMarried: boolean;
} = {
company: "Programming Hero",
firstName: "Sazid",
lastName: "Persian",
isMarried: true,
};
- If the situation is like we want to keep the company name fixed we will use string literal types
// explicit and optional type
const user: {
company: "Programming Hero"; // this programming hero will become a type
firstName: string;
middleName?: string;
lastName: string;
isMarried: boolean;
} = {
company: "Programming Hero", // if we ant to write anything else except the defined literal types it will show type error
firstName: "Sazid",
lastName: "Persian",
isMarried: true,
};
- we can access the properties form the object. If we define a object in one file and export we can access any property of the object in any other files like this

// explicit and optional type
const user: {
company: "Programming Hero";
firstName: string;
middleName?: string;
lastName: string;
isMarried: boolean;
} = {
company: "Programming Hero",
firstName: "Sazid",
lastName: "Persian",
isMarried: true,
};
user.company;
user.firstName;
user.isMarried;
user.lastName;
user.middleName;
- Making string literal using readonly method. its also called access modifier
// explicit and optional type
const user: {
// company: "Programming Hero"; // this programming hero will become a type
// this type can be made using read only as well
readonly company: string;
firstName: string;
middleName?: string;
lastName: string;
isMarried: boolean;
} = {
company: "Programming Hero", // if we ant to write anything else except the defined literal types it will show type error
firstName: "Sazid",
lastName: "Persian",
isMarried: true,
};
// we can access the properties form the object. If we define a object in one file and export we can access any property of the object in any other files like this
// user.company = "PH"; // cant change because it is made readonly
user.firstName;
user.isMarried;
user.lastName;
user.middleName;
1-6 Functions In Typescript
- Functions are the building Blocks
- There are two types of functions in js
- Normal Function
- Arrow Function
- Normal Function without Ts
// Normal Function
function add(num1, num2) {
return num1 + num2;
}
add(2, true);
- Normal Function with Ts
function add(num1: number, num2: number): number {
return num1 + num2;
}
add(2, 3);
- Arrow Function with Ts
const addArrow = (num1: number, num2: number): number => num1 + num2;
- Setting default value
function add(num1: number, num2: number = 10): number {
return num1 + num2;
}
add(2, 3);
- when a function is written inside an object it is called method
- object --> function --> method
const poorUser = {
name: "Sazid",
balance: 0,
// inside object arrow function do not work since we have to use "this" so we are using anonyms normal function
addBalance(balance: number): string {
return `My new Balance Is ${this.balance + balance} `;
},
};
- Callback Function Using TS
const arr: number[] = [1, 2, 3, 4];
const newArray: number[] = arr.map((elem: number): number => elem * elem);
1-7 Spread and Rest Operator

-
We are getting this error since we have declared in another file but files are kept in one folder and ts is making it global and accessing it and showing The error.
-
for practice we will do like this
{
const poorUser = "";
}
- Spread Operator
// Spread Operator
const bros1: string[] = ["Sazid", "Pazid", "Mazid", "Dazid"];
const bros2: string[] = ["Tonmoy", "Monmoy", "Chonmoy", "Donmoy"];
// bros1.push(bros2)
// this is not right method since it will end up in a messed array
// output : ["Sazid", "Pazid", "Mazid", "Dazid", ["Tonmoy", "Monmoy", "Chonmoy", "Donmoy"]];
// this is wrong since we want to push the values only so we have to use spread operator
bros1.push(...bros2);
const mentor1 = {
typescript: "Mezba",
redux: "Mir",
dbms: "Mizan",
};
const mentor2 = {
prisma: "Firoz",
next: "Tonmoy",
cloud: "Nahid",
};
const mentorList = {
...mentor1,
...mentor2,
};

-
after doing the spread operator the mentorList will automatically infer the types
-
Rest Operator
// non-rest
const greetFriends = (friend1: string, friend2: string, friend3: string) => {
console.log(`Hi ${friend1} ${friend2} ${friend3}`);
};
greetFriends("abul", "kabul", "babul");
- here is a problem if friend increases we haver to declare parameters manually, this is not right, here rest operator comes with a solution
const greetFriends = (...friends: string[]) => {
friends.forEach((friend: string) => console.log(`hi ${friend}`));
};
greetFriends("abul", "kabul", "babul");
1-8 Destructuring-In-Typescript
-
Two Types of Destructuring
- Object Destructuring
// Object Destructuring const user = { id: 123, name: { firstName: "Shah", middleName: "Nawaz", lastName: "Sazid", }, contactNo: "0170000000000", address: "Uganda", }; const { id, name: { middleName }, } = user; // while doing it if any spelling error it will say that this do not exist in type // we can use alias as well const { name: { middleName: midName }, contactNo: phoneNumber, } = user; // here we can not declare types while destructuring like this const {name: { middleName: string }} = user; since ts can smartly detect the middleName should be which type- Array Destructuring
// Array Destructuring const myFriends = ["chandler", "joey", "ross", "kosh", "singara", "bulbuli"]; const [a, b, c, d, e, f] = myFriends; // output : "chandler", "joey", "ross", "kosh", "singara", "bulbuli" const [, , , , , besFriend] = myFriends; // output : "bulbuli" const [, , , , ganduFriend] = myFriends; // output : "singara" const [, , , , ...ganduFriends] = myFriends; // output : ["singara","bulbuli"] const [, , kharapBondu, ...rest] = myFriends; // output : kharapBondu = "ross" rest = ["kosh", "singara", "bulbuli"]
1-9 Type Alias In Typescript
const student1: {
name: string;
age: number;
gender: string;
contactNo: string;
address: string;
} = {
name: "Sazid",
age: 50,
gender: "male",
contactNo: "01999999999999",
address: "Dhaka",
};
const student2: {
name: string;
age: number;
gender: string;
address: string;
} = {
name: "Bazid",
age: 69,
gender: "female",
address: "Dhaka",
};
-
Defining types multiple times is a hassle so here comes the type alias with the solution
-
we will define types in one place and use it in different places
-
Using TypeAlias
// using type alias
type Student = {
name: string;
age: number;
gender: string;
contactNo?: string;
address: string;
};
const student1: Student = {
name: "Bazid",
age: 69,
gender: "female",
address: "Dhaka",
};
const studen2: Student = {
name: "Sazid",
age: 50,
gender: "male",
contactNo: "01999999999999",
address: "Dhaka",
};
- we can create type alias using string, boolean and so on as well
// we can create variety of type alias
type UserName = string;
type IsAdmin = boolean;
const userName: UserName = "Sazid";
const isAdmin: IsAdmin = true;
- Type alias in Function
// type alias in Function
// without type alias
const add = (num1: number, num2: number): number => num1 + num2;
// with type alias
type Add = (num1: number, num2: number) => number;
const add1: Add = (num1, num2) => num1 + num2;
1-10 Union and Intersection Types
-
Union Types
- Union type is same as js or operator and it is written by "|"
// union Types type FrontendDeveloper = "fakibazDeveloper" | "juniorDeveloper"; //this is string literal Types type FullstackDeveloper = "frontendDeveloper" | "expertDeveloper"; type Developer = FrontendDeveloper | FullstackDeveloper; // Union Types can be written to make different types union as well const newDeveloper: FrontendDeveloper = "juniorDeveloper"; type User = { name: string; email?: string; gender: "male" | "female"; bloodGroup: "O+" | "A+" | "C+"; // here string literal is used and the options are made using union types }; const user1: User = { name: "persian", gender: "male", bloodGroup: "O+", }; -
Intersection types
- Intersections means common properties
- Its like and of js. like this and this
- "&" is used to write intersection types
// intersection type FrontendDeveloper = { skill: string[]; designation1: "Frontend Developer"; }; type BackendDeveloper = { skill: string[]; designation2: "Backend Developer"; }; type FullstackDeveloper = FrontendDeveloper & BackendDeveloper; const fullstackDeveloper: FullstackDeveloper = { skill: ["HTML", "CSS", "EXPRESS"], designation1: "Frontend Developer", designation2: "Backend Developer", };
1-11 Ternary, Optional Chaining , & Nullish Coalescing Operator
- " ? " This bad boy will be called in different names based on the usages
- When "?" is used for making decision it is called ternary operator
- If a property is exist or not check by "?" is called optional chaining
- "?" it can be used as nullish Coalescing Operator
-
For running the ts automatically we will use TS-NODE-DEV (TS-NODE-DEV)[https://www.npmjs.com/package/ts-node-dev]
-
Install "npm i -g ts-node-dev" installed globally for all time use
-
Run this command "ts-node-dev --respawn --transpile-only .\module1\src\1 .11.ts"
-
Without Ternary Operator
const age: number = 15;
// bangla niom
if (age >= 18) {
console.log("Adult");
} else {
console.log("Not Adult");
}
- Using Ternary Operator
// using ternary operator
const isAdult = age >= 18 ? "Adult" : "Not Adult";
console.log(isAdult);
- Nullish Coalescing Operator
- When Decision is made based on Null or Undefined Nullish is used
- If the value is n ull or undefined we will set a default value then we will use nullish
const isAuthenticated = undefined;
// nullish
const result1 = isAuthenticated ?? "Guest";
// difference with ternary
const result2 = isAuthenticated ? isAuthenticated : "Guest";
console.log({ result1 }, { result2 });
- Optional Chaining
// optional Chaining
const permanentAddress =
user?.address?.permanentAddress ?? "No Permanent Address";
console.log({ permanentAddress });
1-12 Never Unknown and Nullable Types
-
Nullable type
- When a Variable Type Is Null Its Called Nullable Type
- ist like searching specific things when searched and when the search is not done null is send it should show all the data. we are explicitly tel;ling its null
const searchName = (value: string | null) => { if (value) { console.log("Searching"); } else { console.log("There Is Nothing To Search"); } }; searchName(null); -
Unknown Type
- its like we do not know the type for now but we will know in future. in this case we will use "Unknown Type"
- In future we will use typeof to detect the type in run time
const getSpeedInMeterPerSecond = (value: unknown) => { if (typeof value === "number") { const convertedSpeed = (value * 1000) / 3600; console.log(`The Speed Is ${convertedSpeed}`); } else if (typeof value === "string") { const [result, unit] = value.split(" "); console.log(result); const convertedSpeed = (parseFloat(result) * 1000) / 3600; console.log(`The Speed Is ${convertedSpeed}`); } else { console.log(`Wrong Input`); } }; getSpeedInMeterPerSecond(1000); getSpeedInMeterPerSecond(`1000 kmh^-1`); getSpeedInMeterPerSecond(null); -
Never Type
- Means when a function will never return anything it is called Never Type
const throwError = (msg: string): never => {
throw new Error(msg);
};
throwError("Mshkil Se Error Ho Gaya ");