Automation QA Testing Course Content

TypeScript

TYPESCRIPT 

TOPICS:

1. Overview on Type Script
2. Environment Setup on Windows
3. Variables
4. Data Types in TypeScript
5. Operators in TypeScript
6. Strings
7. Conditional Statements in TypeScript
8. Looping statements in TypeScript
9. Arrays in TypeScript
10. Tuple in TypeScript
11.TypeScript Functions
12. Classes, Objects and Methods
13. Inheritance
14. Interface
15. Modules

=======================================================
Overview on Type Script

What is TypeScript?

  • TypeScript is an open-source object-oriented language developed and maintained by Microsoft.
  • TypeScript is a superset of JavaScript that compiles to plain JavaScript.
  • Basically, TypeScript is the ES6 version of JavaScript with some additional features.
  • Official website: https://www.typescriptlang.org

Why TypeScript?

  • Before TypeScript, JavaScript is well established in the market.
  • Using JS we can develop both client and server side applications using different frameworks like:

             Angular or React.js (Client side application frameworks)

                       Node.js (Server side application framework)

  • JavaScript is a dynamic programming language with no type system.
  • We need a language with type system which increases the code quality, readability and makes it an easy to maintain and refactor code base.
  • More importantly, errors can be identified at compile time rather than at run time.
  • So, without the type system, it is difficult to scale JavaScript to build complex applications.
  • Hence, the reason to use TypeScript is that it supports type system and allows JavaScript to be used at scale to build complex applications.

How to use TypeScript?

  • A TypeScript code is written in a file with .ts extension and then compiled into JavaScript using the TypeScript compiler.
  • A TypeScript file can be written in any code editor.
  • A TypeScript compiler needs to be installed on your platform. Once installed, the command:
tsc <filename>.ts
  • compiles the TypeScript code into a plain JavaScript file.
  • JavaScript files can then be included in the HTML and run on any browser.

Example

tsc Sample.ts
Sample.ts → Sample.js

TypeScript Features

  • Cross-Platform: The TypeScript compiler can be installed on any Operating System such as Windows, MacOS and Linux.
  • Object-Oriented Language: TypeScript provides features like Classes, Interfaces, and Modules.
  • Static type-checking: TypeScript uses static typing and helps type checking at compile time. Thus, you can find errors while writing the code without running the script.
  • Optional Static Typing: TypeScript also allows optional static typing in case you are using the dynamic typing of JavaScript.
  • DOM Manipulation: You can use TypeScript to manipulate the DOM for adding or removing elements.
  • ES 6 Features: TypeScript includes most features of planned ECMAScript 2015 (ES 6, 7) such as class, interface, Arrow functions etc.

TypeScript Advantages

  • TypeScript is an open-source language with continuous development and maintenance by Microsoft.

  • TypeScript runs on any browser or JavaScript engine.

  • TypeScript is similar to JavaScript and uses the same syntax and semantics. All of TypeScript's code finally gets converted into JavaScript.

  • TypeScript is also closer in syntax to back-end languages like Java. This helps backend developers write front-end code faster.

  • TypeScript code can be called from an existing JavaScript code. TypeScript also works with existing JavaScript frameworks and libraries without any issues.

  • TypeScript has support for the latest JavaScript features.

Key Differences between JavaScript and TypeScript

  • JavaScript
  • TypeScript
  • JavaScript is a scripting language which helps you create interactive web pages.
  • TypeScript is Object Oriented Programming language & superset of JavaScript.
  • JavaScript code doesn’t need to compile.
  • TypeScript code needs to be compiled.
  • There is no static typing. Ex: var num
  • There is static typing. We can declare variables with data types. Ex: var num : number
  • It does not have interfaces.
  • It has interface.
  • It has no optional parameter feature.
  • It has optional parameter feature.
  • It has no Rest Parameter feature.
  • It has Rest Parameter feature.
  • Generics not supported.
  • Generics supported.
  • Modules not supported.
  • Modules supported.
  • number, string are the objects.
  • Number, string are the interfaces.

=======================================================

Environment Setup on Windows

Pre-requisites

  1. NodeJS

  2. Typescript

  3. Visual Studio Code

Download & Install Node JS on Windows
  • Open Command Prompt (CMD) or PowerShell.
  • Type the following command and press Enter to check the Node.js version:
  • ✅ If installed correctly, you'll see the Node.js version (e.g., v18.17.1).

Step 1: Download Node.js

  • Open your web browser and type download node js.


  • Click on above highlighted link, then you will navigate to below page.
  • Click the LTS version (recommended) to start downloading the installer (.msi file).



Step 2: Run the Installer

  • Locate the downloaded .msi file (usually in the Downloads folder).



  • Double-click to run the installer.


Step 3: Follow the Installation Wizard

  • Click Next on the welcome screen.



  • Accept the license agreement and click Next.



  • Choose the installation location (default is fine) and click Next.



  • Ensure that "Node.js runtime" and "npm package manager" are selected, then click Next.



  • Click Install and wait for the process to complete.

  • Click on Finish.

Step 4: Verify the Installation

  1. Open Command Prompt (CMD) or PowerShell.

  2. Type the following command and press Enter to check the Node.js version:


    ✅ If installed correctly, you'll see the Node.js version (e.g., v18.17.1).

  3. To check the npm (Node Package Manager) version, type:


    ✅ This confirms that npm is installed along with Node.js.

Issue 1: npm.ps1 Cannot Be Loaded (Execution Policy Error)

    When running: npm -v

File C:\Program Files\nodejs\npm.ps1 cannot be loaded because running scripts is disabled on this system.

Reason

Windows PowerShell has a security feature called Execution Policy that blocks scripts from running.

Solution

Step 1: Open PowerShell as Administrator
Step 2: Run the following command
    Set-ExecutionPolicy RemoteSigned
Step 3: Press Y and hit Enter
Now npm works successfully.

Install Typescript
  • npm install -g typescript ( install latest version) npm install -g typescript@3.8 (Install specific version) npm uninstall -g typescript (Un-install typescript) tsc -v => returns version of typescript


Install TSX (To Run TypeScript Directly)

To execute TypeScript files without compiling them first:

npm install -g tsx

Run TypeScript Without Compiling (Recommended)
If you installed tsx, run:
tsx app.ts
(This runs .ts files directly!)

Issue 2: tsc Is Not Recognized

After installing TypeScript globally:

When running: tsc -v

The following error appeared:

tsc : The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.

Reason

The TypeScript compiler path is not refreshed in the terminal.

Solution

Step 1: Close the PowerShell terminal
Step 2: Open a new PowerShell or Command Prompt
Step 3: Run
tsc -v

Verify TypeScript Installation

You can check if TypeScript is installed globally:
    npm list -g typescript

Download Visual Studio Code

  • Open your web browser and type download visual studio code.


  • Click on the "Download for Windows" button.
  • The installer (.exe file) will start downloading automatically.


Step 2: Run the Installer

  • Locate the downloaded .exe file (usually in the Downloads folder).

  • Double-click the file to launch the installer.


Step 3: Follow the Installation Wizard

  1. Click Next on the welcome screen.

  2. Accept the license agreement and click Next.


    3.Choose the installation location (default is fine) and click Next.



4.Select "Add to PATH" (important for command-line usage).

5.Click Install, and wait for the installation to complete.


Step 4: Launch VS Code

1.Once installed, check "Launch Visual Studio Code" and click Finish.

2.VS Code will open. 🎉


Step 5: Verify Installation

  1. Open Command Prompt (CMD) or PowerShell.

  2. Type the following command and press Enter:



    ✅ If installed correctly, it will display the VS Code version.

================================================================
Variables

Variable is a container which can hold data. 

• TypeScript follows the same rules as JavaScript for variable declarations. 

• JavaScript is not a typed language. It means we cannot specify the type of a variable such as number, string, boolean etc. 

• However, TypeScript is a typed language, where we can specify the type of the variables. 

• Variables can be declared using: var, let, and const. 

  • let – for values that can change.

  • const – for values that should not change (constant references).

  • var – old JavaScript way (avoid using it because of scope issues).

• We can declare the variables in four different ways. 

1. both type and initial value 

Example

var employeeName:string="John"; 

2. only the type 

Example

 var employeeName:string;


3. only the initial 

Example

 var employeeName="John";


4. without type and initial value 

Example

 var employeeName;

Rules for Naming Variables

  • Can contain letters, numbers, $, and _

  • Cannot start with a number

  • Cannot be a reserved keyword (let, if, for, etc.)

  • CamelCase is common in JavaScript/TypeScript: firstName, userCount

In TypeScript (and JavaScript), var, let, and const are used to declare variables, but they behave differently in terms of scope, reassignment, and hoisting. Understanding these differences is important for writing clean, predictable, and bug-free code.

1)  Scope

  • var → Function scoped
  • let & const → Block scoped

Example

function test() {
  if (true) {
    var a = 10;
    let b = 20;
    const c = 30;
  }

  console.log(a); // ✅ works
  console.log(b); // ❌ error
  console.log(c); // ❌ error
}

2)  Declaration / Value Assignment
  • var → can declare without value
  • let → can declare without value
  • const → must assign value at declaration

Example

var x;
let y;
const z = 10; // ✅ must assign

const a; // ❌ error

3)  Re-declaration

  • var → allowed
  • let → NOT allowed
  • const → NOT allowed

Example

var a = 10;
var a = 20; // ✅ allowed

let b = 10;
// let b = 20; ❌ error

const c = 10;
// const c = 20; ❌ error


4) Re-assignment (Re-initialization)
  • var → allowed
  • let → allowed
  • const → NOT allowed

Example

var a = 10;
a = 20; // ✅
let b = 10;
b = 20; // ✅
const c = 10;
// c = 20; ❌ error

Important:

const obj = { name: "Harshini" };
obj.name = "Venkateswari"; // ✅ allowed


5) Hoisting
👉 Hoisting = variables are moved to top during execution
  • Hoisted with undefined

var:

Example

console.log(a); // undefined
var a = 10;

let & const:

  • Hoisted but in Temporal Dead Zone (TDZ)
  • Cannot access before declaration

Example

console.log(b); // ❌ error
let b = 10;

console.log(c); // ❌ error
const c = 20;


Final Summary Table
Featurevarletconst
ScopeFunctionBlockBlock
Declare w/o valueYesYes❌ No
Re-declaration✅ Yes❌ No❌ No
Re-assignment✅ Yes✅ Yes❌ No
HoistingYes (undefined)Yes (TDZ)Yes (TDZ)

================================================================

TypeScript Data Types

Type / Data Type, Annotations & Type Inference

What is a Data Type?

data type defines the type of value a variable can store.

Example

let age: number = 30;

  • number → Data Type
  • It tells TypeScript that age should store only numeric values

👉 If you try:

age = "hello"; // ❌ Error

What is Type Annotation?

Type Annotation means explicitly telling TypeScript what type a variable should be.

Example

let age: number = 30;

  • : number → Type Annotation

👉 You are manually defining the type.

What is Type Inference?

Type Inference means TypeScript automatically guesses the type based on the assigned value.

Example

let age = 30;

  • No type is written
  • TypeScript automatically understands → age is of type number

👉 So internally it behaves like:

let age: number = 30;


TypeScript supports two main categories of data types: Built-in and User-defined.


1. Built-in Types

These are the predefined types available in TypeScript.

  • Number → Represents both integers and floating-point numbers

Example

let age: number=25; let price=25.5; let big=4234234234; console.log("Age:",age); // Age: 30 console.log("Price:",price); console.log("Big Number:",big); console.log(typeof(age)) //number console.log(typeof age) //number

  • String → Represents textual data.

 1. SingleQuote ('')
 2. DoubleQuote (" ") 
3. Backtick(`

Example

let firstName:string="John";
let lastName:string='Kenedy';
//console.log("Hello", firstName, lastName); // Hello John Kenedy.
let greeting:string=`Hello ${firstName} ${lastName}`;
console.log(greeting);

  • Boolean → Represents true or false.

Example

let isActive: boolean = true;

  • Void → Used when a function does not return a value.

Example

function greet(): void { console.log("Hello"); }

  • Null → Represents a null value.

Example

let data: null = null;


  • ANY TYPE

    loses TypeScript benefits

Example

let value: any="Welcome"; console.log(typeof(value)) value=100; console.log(typeof(value)) value=true; console.log(typeof(value)) console.log(value);


  • UNION TYPE - Combine multiple types

Example

let id:number | string | boolean; id="ABC123"; console.log(id); id=12345 console.log(id); id=true console.log(id);
  • VOID TYPE

     Used for functions that don't return anything

Example

function show():void { console.log("Welcome"); } show();



2. User-defined Types

These are types created by the developer to model complex data structures.

  • Array → Represents a collection of values.

Example

let numbers: number[] = [1, 2, 3];
  • Tuple → An array with a fixed number of elements, each with a specific type.
Example
let person: [string, number] = ["Alice", 25];
  • Enum → A set of named constants.

Example

enum Color { Red, Green, Blue }
let c: Color = Color.Green;
  • Functions → Can be typed by defining parameter and return types.

Example

function add(a: number, b: number): number {
  return a + b;
}
  • Class → Blueprint for creating objects.

Example

class Person {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
}
  • Interface → Defines the structure of an object.

Example

interface User {
  id: number;
  name: string;
}
let user: User = { id: 1, name: "Alice" };
================================================================

TypeScript Operators

There are different types of JavaScript operators:

  • Arithmetic Operators
  • Assignment Operators
  • Comparison Operators
  • Logical Operators

TypeScript Arithmetic Operators

Arithmetic Operators are used to perform arithmetic on numbers:

 Example

let a = 3;
let x = (100 + 50) * a;


  • A typical arithmetic operation operates on two numbers.
  • The two numbers can be literals, variables or expressions.
  • In arithmetic, the division of two integers produces a quotient and a remainder.

  • In mathematics, the result of a modulo operation is the remainder of an arithmetic division.

Operators and Operands

  • The numbers (in an arithmetic operation) are called operands.
  • The operation (to be performed between the two operands) is defined by an operator.


---------------------------------------------------------

TypeScript Assignment Operators

  • Assignment operators assign values to JavaScript variables.
  • The Addition Assignment Operator (+=) adds a value to a variable.

Assignment

let x = 10;
x += 5;




---------------------------------------------------------

TypeScript Comparison Operators



---------------------------------------------------------

JavaScript Logical Operators


================================================================

TypeScript Strings

In TypeScript, string methods are built-in functions that let you perform actions on text, such as searching, replacing, splitting, or changing case. They work the same way as in JavaScript since TypeScript is built on top of JavaScript. Examples include toUpperCase(), includes(), and replace().

Method Description Example
charAt(index) Returns the character at the specified position. "Hello".charAt(1)e
charCodeAt(index) Returns the Unicode value of the character at the given position. "A".charCodeAt(0)65
concat(str1, str2, …) Joins two or more strings. "Hello".concat(" ", "World")Hello World
includes(searchValue) Checks if the string contains the given text. "Hello".includes("ell")true
endsWith(searchValue) Checks if the string ends with the given text. "Hello".endsWith("lo")true
startsWith(searchValue) Checks if the string starts with the given text. "Hello".startsWith("He")true
indexOf(searchValue) Returns the position of the first occurrence. "Hello".indexOf("l")2
lastIndexOf(searchValue) Returns the position of the last occurrence. "Hello".lastIndexOf("l")3
match(regex) Matches the string with a regex and returns an array. "Hello".match(/l/g)["l", "l"]
matchAll(regex) Returns all matches of a regex as an iterator. Array.from("Hello".matchAll(/l/g))
padEnd(targetLength, padString) Pads the string at the end to reach the target length. "5".padEnd(3, "0")500
padStart(targetLength, padString) Pads the string at the start to reach the target length. "5".padStart(3, "0")005
repeat(count) Repeats the string multiple times. "Hi".repeat(3)HiHiHi
replace(searchValue, newValue) Replaces the first match with a new value. "Hello".replace("l", "x")Hexlo
replaceAll(searchValue, newValue) Replaces all matches with a new value. "Hello".replaceAll("l", "x")Hexxo
search(regex) Searches for a match and returns the position. "Hello".search(/l/)2
slice(start, end) Extracts part of the string. "Hello".slice(1, 4)ell
split(separator) Splits the string into an array. "a,b,c".split(",")["a", "b", "c"]
substring(start, end) Returns part of the string between two indexes. "Hello".substring(1, 4)ell
toLowerCase() Converts the string to lowercase. "HELLO".toLowerCase()hello
toUpperCase() Converts the string to uppercase. "hello".toUpperCase()HELLO
trim() Removes spaces from both ends. " Hi ".trim()Hi
trimStart() Removes spaces from the start. " Hi".trimStart()Hi
trimEnd() Removes spaces from the end. "Hi ".trimEnd()Hi
valueOf() Returns the primitive value of a string. new String("Hello").valueOf()Hello

 Fixing “Property 'repeat' does not exist on type 'string'” in TypeScript

Step 1: Understand the Problem

  • The method repeat() is part of ES2015 (ES6).

  • By default, TypeScript compiles using ES5.

  • In ES5, repeat() does NOT exist.

👉 So TypeScript throws an error.


Step 2: Add tsconfig.json

Create a file named tsconfig.json in the same folder:

{
"compilerOptions": {
"target": "es2015",
"lib": ["es2015", "dom"]
}
}

Step 3:
Run: tsc
================================================================

TypeScript Conditional Statements

Conditional statements are used to perform different actions based on different conditions.

In TypeScript we have the following conditional statements:

  • Use if to specify a block of code to be executed, if a specified condition is true
  • Use else to specify a block of code to be executed, if the same condition is false
  • Use else if to specify a new condition to test, if the first condition is false
  • Use switch to specify many alternative blocks of code to be executed

The if Statement

Use the if statement to specify a block of TypeScript code to be executed if a condition is true.

Syntax

if (condition) {
  //  block of code to be executed if the condition is true
}

 Note : that if is in lowercase letters. Uppercase letters (If or IF) will generate a TypeScript error.

✅ if Statement

Used to execute code if a condition is true.

let age:number = 18;

if (age >= 18) {

console.log("You are an adult.");

}

output

You are an adult.

------------------------------------------------------------------------

The else Statement

Use the else statement to specify a block of code to be executed if the condition is false.

if (condition) {
  //  block of code to be executed if the condition is true
else {
  //  block of code to be executed if the condition is false
}

 if...else Statement

Executes one block if the condition is true, and another if it's false.

let age:number = 16;

if (age >= 18) {

console.log("You are an adult.");

} else {

console.log("You are a minor.");

}

output

You are a minor.
------------------------------------------------------------------------

The else if Statement

Use the else if statement to specify a new condition if the first condition is false.

Syntax

if (condition1) {
  //  block of code to be executed if condition1 is true
else if (condition2) {
  //  block of code to be executed if the condition1 is false and condition2 is true
else {
  //  block of code to be executed if the condition1 is false and condition2 is false
}

 if...else if...else Statement

Used to check multiple conditions.

let score:number = 85;

if (score >= 90) {

console.log("Grade A");

} else if (score >= 80) {

console.log("Grade B");

} else if (score >= 70) {

console.log("Grade C");

} else {

console.log("Fail");

}

output

Grade B

------------------------------------------------------------------------

The Switch Statement

Use the switch statement to select one of many code blocks to be executed.

Syntax

switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}

This is how it works:

  • The switch expression is evaluated once.
  • The value of the expression is compared with the values of each case.
  • If there is a match, the associated block of code is executed.
  • If there is no match, the default code block is executed.

 switch Statement

An alternative to if...else if...else for comparing the same variable to multiple values.

let day = "Tuesday";

switch (day) {

case "Monday":

console.log("Start of the week");

break;

case "Tuesday":

console.log("Second day");

break;

case "Friday":

console.log("Almost weekend!");

break;

default:

console.log("It's just a regular day");

}

output
Second day
🔹 Use break to stop the execution once a case matches.
🔹 default is optional and runs when no case matches.

================================================================

TypeScript Looping statements

Loops 

While 

• Do ...while 

• For 

• Jumping statements with Loops

   - Break 

  - Continue 


The While Loop

The while loop in TypeScript runs as long as the given condition is true.

It’s useful when you don’t know ahead of time how many times the loop should run.

Syntax

while (condition) { // code block to be executed }

Example

let count : number= 1; while (count <= 5) { console.log("Count is:", count); count++; }

Output

Count is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5

⚠️ Important Notes:

• The loop will continue until the condition becomes false. • Be sure to update your condition inside the loop, or you’ll get an infinite loop. Infinite Loop Example (⚠️ Avoid This!) while (true) { // This runs forever unless a break is used console.log("Still running..."); break; // used to stop the infinite loop } =========================== The Do While Loop The do...while loop in JavaScript is similar to a while loop, but it runs the code block

at least once, even if the condition is false from the beginning.

Syntax

do { // code block to execute } while (condition);

Example

let count:number = 1; do { console.log("Count is:", count); count++; } while (count <= 5);

Output

Count is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5

======================================

The For Loop A loop is a way to repeat a block of code multiple times until a certain condition is met.

Syntax

for (initialization; condition; increment) { // code to be executed }

Example

for (let i = 0; i < 5; i++) { console.log("Number:", i); }

Output

Number: 0 Number: 1 Number: 2 Number: 3 Number: 4

🔍 How it works:

1. Initialization: Executes once before the loop starts (let i = 0). 2. Condition: Checked before each iteration. If true, the loop runs (i < 5). 3. Increment: Executes after each loop iteration (i++).

for...of Loop

Used to iterate over values of an array or iterable objects.

Example

let fruits: string[] = ["Apple", "Banana", "Mango"];  for (let fruit of fruits) { console.log(fruit); }

Output

Apple Banana Mango


for...in Loop

Used to iterate over keys (indexes or property names) of an object or array.

Example

let fruits: string[] = ["Apple", "Banana", "Mango"];  for (let index in fruits) { console.log(index); }

Output

0 1 2

=========================

Break   Break is used to exit the loop immediately, even if the loop condition is still true.

Example

for (let i = 1; i <= 5; i++) { if (i === 3) { break; // exits loop when i is 3 } console.log(i); }

Output

1, 2

=========================

Continue   continue is used to skip the current iteration of the loop and move to the next one.

Example

for (let i = 1; i <= 5; i++) { if (i === 3) { continue; // skips printing when i is 3 } console.log(i); }

Output

1, 2, 4, 5

===============================================================

Handling Object Keys in TypeScript (keyof typeof)

Why We Use keyof typeof in a for...in Loop (TypeScript)

Problem Statement

Consider the following code:

let person = { name: "alice", age: 25 };

for (let key in person) {
  console.log(person[key]); // ❌ May throw error in TypeScript
}

Error:

Element implicitly has an 'any' type...

 Why This Error Occurs

🔹 Step 1: for...in Loop Behavior

for (let key in person)

👉 Here, key is always of type:

string

🔹 Step 2: Object Keys

let person = { name: "alice", age: 25 };

👉 Valid keys are:

"name" | "age"

 The Issue

TypeScript thinks:

❌ “You are using a general string as a key, but the object only has specific keys.”

So this becomes unsafe:

person[key]

 Solution: Use keyof typeof

let person = { name: "alice", age: 25 };

for (let key in person) {
  console.log(person[key as keyof typeof person]);
}

 What Does keyof typeof Mean?

  • typeof person → gives object type

    { name: string; age: number }
    
  • keyof typeof person → extracts keys

    "name" | "age"
    

 Meaning

key as keyof typeof person

👉 Tells TypeScript:

 “This key will always be one of the valid keys of the object.”


 Key Takeaway

  • for...in returns string keys

  • TypeScript expects specific keys

  • Use keyof typeof to ensure type safety

👉 We use keyof typeof in a for...in loop to tell TypeScript that the key is a valid property of the object.

================================================================

TypeScript Arrays

  An array is a special type of variable that stores multiple values.

- The values can be of the same data type or different data types.

- Arrays are declared using `[]` or the generic `Array<T>` type.

- Indexing starts from 0.

- Arrays are an ordered collection of elements.

Approach 1: using leteral

let names:string[]= []; // Declaration

//Initilization/assigning values

names[0]="John";

names[1]="Smith";

names [2]="Peter";

names[3]="Scott";

// declaration+initilization

let names: string[]=["John", "Smith", "Peter", "Scott"]; 

console.log(names);

Approach 2: Using the generic Array<T> type

let empNames: Array<string>=["John", "Smith", "Peter", "Scott"];

let empIds: Array<number>=[101, 102, 103,104);

let data: Array<string | number>=["John", 101, "Smith", 102, "Peter", "Scott"];

let mixedData: Array<any>=[1, "John", true, null);


console.log(empNames);//["John", "Smith", "Peter", "Scott"]

console.log(empNames[1]);//Smith

 

Example 1: Iterating over an array using a traditional for loop

console.log("Size of an Array:", empNames.length); //4 (How many values stored)

console.log("Employee Names......");

for(let i=0; i<empNames.length; i++)   //i<=empNames.lenght-1

{

    console.log(empNames[i]);   // i is representing an index

}

 Example 2: Iterating using the 'for...in' loop (indexes)

console.log("Empployee Ids.....");

for(let i in empIds)

{

    console.log(empIds[i]);

} 

Example 3: Iterating using the 'for...of' loop (values)

console.log("Mixed Data.....");

for(let value of data)

{

  console.log(value);

}

Example 4: Passing an Array to the function

//Search an element in an array using function

{

function search(ele:number, arr:number[]): boolean

{

for(let i=0; i<arr.length; i++)

if(arr[i]===ele)

{

return true; // Element found

}

}

return false;

}

let arr:number[] = [10,20,30,40,50];

console.log(search (30,arr)); // true

console.log(search (100, arr)); // false

Example 5: A functions takes an Array and returns an array

function capitalizeWords(arr: string[]): string[]
{
let result:string[]=[];
}
for(let i=0;i<arr.length;i++)
}
result[i]=arr[i].toUpperCase();
return result; I
let words: string[]=["hello", "world", "TypeScript"];
console.log(capitalizeWords (words));

===============================================================

Array Methods

TypeScript Tuple

Tuple is a new data type which includes multiple set of values of different data types.

It represents a heterogeneous collection of values.

 Tuple type variable

var employee = [1, "Steve"];

OR

var employee: [number, string] = [1, "Steve"];

=====================

Declare tuple 

var employee=[101,"John",50000]; 

(OR)

var employee:[number,string,number]=[101,"John",50000]; 

=====================

Accessing Tuple 

console.log(employee[0]); //101 

console.log(employee(1]); //"John" 

console.log(employee[2]);//50000 

====================

Add elements in to tuple - push() 

var employee:[number,stringsnumber]=[101,"John",50000];

 console.log("Original tuple:"+employee); 

employee.push(102,"Scott",70000); 

console.log("After adding new elements:"+employee);  

Output:
Original tuple: 101, "John",50000
After adding new elements: 101, "John",50000,102, "Scott",70000

====================

Ways to Remove Elements from a Tuple

1. Using pop() – removes last element

let user: [number, string, boolean] = [1, "Alice", true];

user.pop();

console.log(user); // [1, "Alice"]

2. Using shift() – removes first element

let user: [number, string, boolean] = [1, "Alice", true];

user.shift();

console.log(user); // ["Alice", true]

====================

Updating Elements in a Tuple

Example 1 – Basic Update

let user: [number, string, boolean] = [1, "Alice", true];

// Update second element

user[1] = "Bob";

console.log(user); // [1, "Bob", true]

Example 2 – Update Multiple Elements

let employee: [number, string, string] = [101, "John", "Developer"];

// Update name and role

employee[1] = "David";

employee[2] = "Manager";

console.log(employee); // [101, "David", "Manager"]

Example 3 – With Union Types

let data: [string | number, boolean] = ["Active", true];

// Update string to number

data[0] = 200;

console.log(data); // [200, true]

====================

 What is a Tuple Array?

A tuple array means:

  • An array of tuples (each element in the array is a tuple).

  • Useful when you need to store multiple fixed-structured records.

Example 1 – Basic Tuple Array

let employees: [number, string][];

// Assign values

employees = [

[101, "Alice"],

[102, "Bob"],

[103, "Charlie"]

];

console.log(employees);

// [[101, "Alice"], [102, "Bob"], [103, "Charlie"]]

Example 2 – Adding New Tuple

employees.push([104, "David"]);

console.log(employees);

// [[101, "Alice"], [102, "Bob"], [103, "Charlie"], [104, "David"]]

Example 3 – Iterating Over Tuple Array

for (let [id, name] of employees) {

console.log(`ID: ${id}, Name: ${name}`);

Output:

ID: 101, Name: Alice

ID: 102, Name: Bob

ID: 103, Name: Charlie

ID: 104, Name: David

========================

  1. Tuple with Rest Elements

  • Allows tuples to hold fixed + variable parts.

let skills: [string, ...string[]] = ["Frontend"];

skills.push("HTML", "CSS", "JS");

console.log(skills); // ["Frontend", "HTML", "CSS", "JS"]

=======================

2. Readonly Tuples (immutable tuples)

let point: readonly [number, number] = [10, 20];

// point[0] = 30; ❌ Error: Cannot assign to readonly tuple

=======================

3. Destructuring Tuples

let employee: [number, string] = [101, "Alice"];

let [id, name] = employee;

console.log(id, name); // 101 "Alice"

=======================

4. Optional Elements in Tuples

let person: [string, number?];

person = ["John"];

person = ["John", 25]; 

===============================================================

TypeScript Functions

Functions are the primary blocks of any program. 

• Advantages of function: 

Code reusability: We can call a function several times without writing the same block of code again. The code reusability saves time and reduces the program size. 

Less coding: Functions makes our program compact. So, we don't need to write many lines of code each time to perform a common task. 

Easy to debug: It makes the programmer easy to locate and isolate faulty information. 

Functions are 3 types:

1. Named Functions

2. Anonymous Functions

3. Arrow Functions


Types of Functions

1. Named Functions

A named function is one where you declare and call a function by its given name.

Syntax

function functionName(parameter): returnType

{

  // block of code

}

functionName();

1. Named Function

function display(){

console.log("Welcome to typescript");

}

 display(); //Welcome to typescript

2. Named Function include parameter types and return type:

function Sum(x:number, y:number): number{

return x+y;

}

var res=Sum(100,200);

console.log(res);//300

3. Named Function with Rest parameters:

        Rest parameters dont restrict the number of values that you can pass to a function.

function addNumbers(...nums:number[])

{

  let i;

  let sum:number = 0;

  for(i = 0;i<nums.length;i++){

    sum = sum + nums[i];

  }

  console.log("sum of the numbers",sum)

}

//function invocation

addNumbers(1,2);

addNumbers(1,2,3);

addNumbers(10,20,30,40,50);


4. Named Function with Rest parameters multiple types:

        Rest parameters dont restrict the number of values that you can pass to a function.

function findElements(...elements: (number | string) []): number

{

return elements.length;

}

console.log(findElements(3,"john", 2, 1, "scott")); //5

console.log(findElements (10,20,30,40,50,60,70)); //7

console.log(findElements("abc", "xyz")); //2

5. Named Function with Optional Parameters:

            Optional parameters are parameters that are not mandatory when calling the function. Optional parameters should be at the end

 In TypeScript, optional parameters are defined using ?.

function greet(name: string, age?: number): void {

  if (age) {

    console.log(`Hello ${name}, you are ${age} years old`);

  } else {

    console.log(`Hello ${name}`);

  }

}

//Function calling

greet("John");        // Hello John

greet("John", 25);    // Hello John, you are 25 years old

6. Named Function with default Parameters:

            Default parameters allow you to assign a default value to a function parameter.

If no value is passed while calling the function, the default value is used automatically.
If value is passed, it overrides the default.

function greet(name: string, age: number = 25): void {

  console.log(`Hello ${name}, you are ${age} years old`);

}

//Function calling

greet("John");        // Hello John, you are 25 years old (default used)

greet("John", 30);    // Hello John, you are 30 years old

2. Anonymous Function

An anonymous function is one which is defined as an expression.

This expression is stored in a variable. So, the function itself does not have a name.

These functions are invoked using the variable name that the function is stored in.

Syntax

let variable = function(parameters)

{

    // function body

};

variable(); // Calling the function

Anonymous Function

var greeting=function(){

console.log("Welcome to Typescript");

}

greeting(); //Welcome to Typescript

2. Anonymous Function includes parameter types and return type.

var Sum=function(x:number,y:number): number{

return x+y;

}

console.log(Sum(10,20));  //30


Function Parameters.

Parameters are values or arguments passed to a function.

In TypeScript, the compiler expects a function to receive the exact number and type of

arguments as defined in the function signature.

If the function expects three parameters, the compiler checks that the user has passed values for

all three parameters i.e. it checks for exact matches..

Types of Parameters

Optional Parameters

Default Parameters

1. Optional Parameters

  • In TypeScript, parameters can be marked as optional by adding a ? after the parameter name.

  • If the argument is not passed, it will be undefined.

Example

function greet(name: string, age?: number): string {

if (age) {

return `Hello ${name}, you are ${age} years old.`;

}

return `Hello ${name}`;

}

console.log(greet("Alice")); // Hello Alice

console.log(greet("Bob", 25)); // Hello Bob, you are 25 years old.

 Rule: Optional parameters must come after required parameters.


2. Default Parameters

  • Default parameters let you assign a value to a parameter if no argument is passed.

Example

function greet(name: string, age: number = 18): string {

return `Hello ${name}, age is ${age}`;

}

console.log(greet("Alice")); // Hello Alice, age is 18

console.log(greet("Bob", 25)); // Hello Bob, age is 25 

 Here, if no age is provided, it defaults to 18.   


Arrow Function

  • Fat arrow notations are used for anonymous functions i.e for function expressions.
  • They are also called lambda functions in other languages.
  • An Arrow Function (=>) is a shorter syntax to write functions in TypeScript (and JavaScript).
  • It is often used for anonymous functions, callbacks, and when you want to preserve the this context.

Syntax:

(parameter1: type, parameter2: type, ...): returnType => expression

Examples of Arrow Functions

1. Basic Arrow Function

let add = (a: number, b: number): number => {

return a + b;

};

console.log(add(5, 10)); // 15 

2. Arrow Function with Implicit Return

If the function has only one statement, you can skip {} and return.

let multiply = (a: number, b: number) => a * b;

console.log(multiply(4, 3)); // 12

3. Arrow Function with One Parameter (no parentheses needed)

  • If you don’t write a type → parentheses are optional for a single parameter.
  • If you write a type → parentheses are required.

let square = (x: number): number => x * x;

console.log(square(6)); // 36

4. Arrow Function with No Parameters

let greet = (): string => "Hello, TypeScript!";

console.log(greet()); // Hello, TypeScript!

5. Arrow Function with Optional Parameters:

            Optional parameters are parameters that are not mandatory when calling the function. Optional parameters should be at the end

 In TypeScript, optional parameters are defined using ?.

let greet=(name: string, age?: number): void =>{

  if (age) {

    console.log(`Hello ${name}, you are ${age} years old`);

  } else {

    console.log(`Hello ${name}`);

  }

}

//Function calling

greet("John");        // Hello John

greet("John", 25);    // Hello John, you are 25 years old

6. Arrow Function with default Parameters:

            Default parameters allow you to assign a default value to a function parameter.

If no value is passed while calling the function, the default value is used automatically.

If value is passed, it overrides the default.

let greet=(name: string, age: number = 25): void =>{

  console.log(`Hello ${name}, you are ${age} years old`);

}

//Function calling

greet("John");        // Hello John, you are 25 years old (default used)

greet("John", 30);    // Hello John, you are 30 years old

7. Arrow Function with Rest parameters multiple types:

        Rest parameters dont restrict the number of values that you can pass to a function.

let findElements=(...elements: (number | string) []): number=>

{

return elements.length;

}

console.log(findElements(3,"john", 2, 1, "scott")); //5

console.log(findElements (10,20,30,40,50,60,70)); //7

console.log(findElements("abc", "xyz")); //2


In TypeScript, functions can have special features like callback functions and function

overloading, making them more powerful and flexible.

Callback Functions

A callback function is a function that is passed as an argument to another function and gets executed later.

Why Use Callback Functions?

Useful when you want a function to execute only after another function completes.

Common in asynchronous operations like API calls, file handling, or event handling.

Synchronous means the code runs in a particular sequence of instructions given in

the program, whereas asynchronous code execution allows to execution of the

upcoming instructions immediately.

//Step:2=>Function that takes callback function as an parameter

function greet(name:string,callback:(message: string)=> void): void

{

console.log(name);

callback("Hello"); // executing the callback function

}

//Step:1=>callback function

function showMessage(message: string)

{

console.log(message);

}

//Step:3=>calling the function by passing the callback function

greet("John", showMessage);


Function Overloading

TypeScript provides the concept of function overloading.

In TypeScript, function overloading allows you to define multiple function signatures with the same name but different parameter types/number.

 However, you can only have one actual implementation of the function.

We can have multiple functions with the same name but different parameter types and return type. However, the number of parameters should be the same.

Syntax of Function Overloading

// 1. Function declarations (signatures)

function add(x: number, y: number): number;

function add(x: string, y: string): string;

// 2. Single implementation

function add(x: any, y: any): any {

return x + y;

}

// Usage

console.log(add(10, 20)); // 30

console.log(add("Hello ", "World")); // Hello World

 Rules of Overloading in TypeScript

  1. You can declare multiple function signatures.

  2. You must provide one implementation that handles all cases.

  3. The implementation must be compatible with all declared signatures.

  4. Unlike Java, return type alone cannot distinguish overloads.


 Overloading can happen in two ways in TypeScript:

  1. Different parameter count

function greet(name: string): string;

function greet(firstName: string, lastName: string): string;

function greet(nameOrFirst: string, lastName?: string): string {

if (lastName) {

return `Hello, ${nameOrFirst} ${lastName}`;

}

return `Hello, ${nameOrFirst}`;

}

console.log(greet("Ramesh")); // Hello, Ramesh

console.log(greet("Ch", "Ramesh")); // Hello, Ch Ramesh

2.Different parameter types

function add(a: number, b: number): number;

function add(a: string, b: string): string;

function add(a: any, b: any): any {

return a + b;

}

console.log(add(5, 10)); // 15

console.log(add("Hello, ", "World!")); // "Hello, World!"


Rest Parameters (…parameter)

  • Rest parameters allow a function to accept any number of arguments as an array.

  • Instead of defining a fixed number of parameters, you use ... before the parameter name.

  • It collects all extra arguments passed into the function into a single array.

Example 

function sum(...numbers: number[]): number {

return numbers.reduce((total, n) => total + n, 0);

}

console.log(sum(1, 2)); // 3

console.log(sum(1, 2, 3, 4, 5)); // 15

 Here, ...numbers gathers all arguments into an array like [1,2,3,4,5].

===============================================================

TypeScript Classes, Objects and Methods

Class:

 A class can include the following:

- Constructor

- Properties

- Methods



A class is a blueprint (or template) for creating objects.

It defines properties (data) and methods (behaviors) that objects will have.

Example 

class Car {

//Properties

brand: string;

year: number;

//constructor

constructor(brand: string, year: number) {

this.brand = brand;

this.year = year;

}

//method

displayInfo(): string {

return `${this.brand} was made in ${this.year}`;

}

}

Here, Car is a class with properties (brand, year) and a method (displayInfo()).

2. Object

  • An object is an instance of a class.

  • When we use the class to create something, that created thing is an object.

  • Each object can have its own property values.

Example 

let car1 = new Car("Toyota", 2020); // object

let car2 = new Car("Honda", 2022); // another object

console.log(car1.displayInfo()); // Toyota was made in 2020

console.log(car2.displayInfo()); // Honda was made in 2022

Here, car1 and car2 are objects of the class Car.

3. Method

  • A method is simply a function defined inside a class.

  • Methods define the behavior of objects.

  • They usually operate on the object’s own properties using this.

Example (from above):

displayInfo(): string {

return `${this.brand} was made in ${this.year}`;

}

displayInfo() is a method because it’s inside the class Car.
It uses this.brand and this.year to access object-specific data.

===================================================================

TypeScript Inheritance

Inheritance is acquiring all the variables and methods from one class to another class.

It helps to reuse the code and establish a relationship between different classes.

1. Parent class ( Super or Base class)

2. Child class (Subclass or Derived class )

A class which inherits the properties is known as Child Class whereas a class whose properties are inherited is known as Parent class.

TypeScript classes can be extended to create new classes with inheritance, using the keyword

Class A{

--------

}

Class B extends A{

-------

}


Example

// Parent class

class Animal {

name: string;

constructor(name: string) {

this.name = name;

}

makeSound(): void {

console.log("Some generic sound...");

}

}

// Child class inheriting from Animal

class Dog extends Animal {

breed: string;

constructor(name: string, breed: string) {

super(name); // calling parent constructor

this.breed = breed;

}

// Overriding parent method

makeSound(): void {

console.log("Woof! Woof!");

}

displayInfo(): void {

console.log(`Name: ${this.name}, Breed: ${this.breed}`);

}

}

// Usage

let myDog = new Dog("Bruno", "German Shepherd");

myDog.makeSound(); // Output: Woof! Woof!

myDog.displayInfo(); // Output: Name: Bruno, Breed: German Shepherd

 Key Points:

extends → used for inheritance.

super() → used to call the constructor of the parent class.

You can override methods in the child class.

The child class can have its own extra properties and methods.

===============================================

Interface

Interface is a structure that defines the contract in your application.

It defines the syntax for classes to follow.

The TypeScript compiler does not convert interface to JavaScript. It uses interface for type checking. This is also known as "duck typing" or "structural subtyping".

An interface is defined with the keyword interface and it can include properties and method declarations using a function or an arrow function.

An interface extends another interface.

A class implements interface.

Example 1: Basic Interface

interface Person {

name: string;

age: number;

}

let user: Person = {

name: "Alice",

age: 25

};

console.log(user.name); // Alice

Here, Person is an interface with name and age.

Any object of type Person must have those properties.

Example 2: Interface with Methods

interface Animal {

name: string;

makeSound(): void; // method signature

}

class Dog implements Animal {

name: string;

constructor(name: string) {

this.name = name;

}

makeSound(): void {

console.log("Woof! Woof!");

}

}

let myDog = new Dog("Bruno");

myDog.makeSound(); // Woof! Woof!

===================================================================

Modules

The files created in typescript have global access, which means that variables declared in one file are easily accessed in another file.

This global nature can cause code conflicts and can cause issues with execution at run-time.

We have export and import module functionality which can be used to avoid global variable, function conflicts.

This feature is available in JavaScript with ES6 release and also supported in typescript.

Example 1: Export and Import

 mathUtils.ts

export function add(x: number, y: number): number {

return x + y;

}

export function multiply(x: number, y: number): number {

return x * y;

}

 app.ts

import { add, multiply } from "./mathUtils";

console.log(add(2, 3)); // 5

console.log(multiply(4, 5)); // 20

Here, mathUtils.ts is a module exporting functions.
app.ts is importing and using them.

Example 2: Default Export

 logger.ts

export default function logMessage(message: string) {

console.log("Log:", message);

}

app.ts

import log from "./logger";

log("Hello Modules!"); // Log: Hello Modules! 

With default export, you don’t need { } during import.

Example 3: Class Export

 shapes.ts

export class Circle {

constructor(public radius: number) {}

area(): number {

return Math.PI * this.radius * this.radius;

}

}

app.ts

import { Circle } from "./shapes";

let c = new Circle(5);

console.log(c.area()); // 78.54

 Key Points about Modules

  1. Each TypeScript file can be a module.

  2. Use export to make variables, functions, or classes available outside.

  3. Use import to bring them into another file.

  4. Supports named exports and default exports.

  5. Helps in writing modular, reusable, and maintainable code.