TYPESCRIPT
TOPICS:
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
➤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
|
|
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
=======================================================
Environment Setup on Windows
Pre-requisites
-
NodeJS
-
Typescript
-
Visual Studio Code
- 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
- 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.
- 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
- 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
Click Next on the welcome screen.
Accept the license agreement and click Next.
3.Choose the installation location (default is fine) and click Next.
Click Next on the welcome screen.
Accept the license agreement and click Next.
Step 4: Launch VS Code
1.Once installed, check "Launch Visual Studio Code" and click Finish.
2.VS Code will open. 🎉
• 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
var
• The variables declared using var are available within the function.
• If we declare them outside the function, then they are available everywhere i.e. they are a global variable.
• If we define them inside a code block, they are still scoped to the enclosing function.
variables can be redefined or updated
-
Can update the value.
-
Can redeclare in the same scope.
-
Function-scoped, not block-scoped (may cause accidental overwrites).
let:
Block-scoped → A variable declared with let
is only accessible within the block {}
where it is defined (e.g., inside an if
block).
Function-scoped when in the outer block → If declared inside a function but outside any smaller block, it can be accessed anywhere inside that function.
Global scope → If declared outside any function, it becomes a global variable but still respects block scope rules.
let
variables can be updated but not redeclared
-
Can update the value.
-
Cannot redeclare in the same scope.
-
Block-scoped (safer than
var
).
const:
Block scope → Accessible only within the { ... }
block in which it’s declared.
Function scope → If declared inside a function but outside any smaller block, it’s available throughout that function.
Global scope → If declared outside of any function, it’s a global constant but still only visible within the module/script.
const
variables cannot be redefined or updated
-
Cannot update the value (for primitives).
-
Cannot redeclare in the same scope.
-
Block-scoped.
-
For objects/arrays, properties or elements can be changed, but the reference cannot be reassigned
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 numeric values.
let age: number = 25;
-
String
→ Represents textual data.
let name: string = "Alice";
Boolean
→ Representstrue
orfalse
.
-
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;
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.
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" };
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.
let a = 3;
let x = (100 + 50) * a;
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.
+=
) adds a value to a variable.Assignment
let x = 10;
x += 5;
let x = 10;
x += 5;
---------------------------------------------------------
TypeScript Comparison Operators
---------------------------------------------------------
JavaScript Logical Operators
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 |
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
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.
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 (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.");
}
let age:number = 18;
if (age >= 18) {
console.log("You are an adult.");
}
output
You are an adult.
------------------------------------------------------------------------
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
}
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.");
}
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.------------------------------------------------------------------------
You are a minor.
The else if Statement
Use the else if
statement to specify a new condition if the first condition is false.
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 (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");
}
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
------------------------------------------------------------------------
Grade B
The Switch Statement
Use the switch
statement to select one of many code blocks to be executed.
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.
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
✅ 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");
}
outputSecond day🔹 Use break
to stop the execution once a case matches.
🔹 default
is optional and runs when no case matches.
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");
}
outputSecond day
break
to stop the execution once a case matches.🔹
default
is optional and runs when no case matches.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++).
=========================
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
An array is a special type of data type which can store multiple values of different data types sequentially using a special syntax.
• There are 2 types of arrays
- Single dimensional
- Two Dimensional
Single dimensional
1. Single Type Array
Example
//Array Declaration and Initialization
var fruitsl:string[]=["apple","mango","banana"];
// initilization
var fruits2:Array<string>;
// declaration
fruits2=["apple","mango","banana"];
console.log(fruitsl);
console.log(fruits2);
Output
['apple', 'mango', 'banana'];
['apple', 'mango', 'banana'];
2. Multi Type Array
Example
var values:(string | number)[]=["apple",100,"orange",10];
console.log(values)
//or
var values1:Array<string | number>=["banana",100,"orange",200];
console.log(values1)
Output
[ 'apple', 100, 'orange', 10 ]
[ 'banana', 100, 'orange', 200 ]
Access Array Elements
Example
var fruits:string[]=['Apple', 'Orange', 'Banana'];
console.log(fruits[0]);
console.log(fruits[1]);
console.log(fruits[2]);
console.log(fruits[3J);// undefined
Output
Apple
Orange
Banana
undefined
Access Array Elements using for loop
console.log("Reading elements using for loop...")for(var i=0;i<fruits.length;i++){console.log(fruits[i]);}
console.log("Reading elements using for loop with in operator...")for(var j in fruits){console.log(fruits[j])}
Output
Reading elements using for loop..
Apple
Orange
Banana
Reading elements using for loop with in operator...
Apple
Orange
Banana
Two Dimensional
Example
//2D Array Declaration and Initialization
var myarray:number[][]=[ [10,20], [30,40], [50,60]] //Using square brackets
console.log(myarray);
Output
[[10, 20], [ 30, 40], [50,60]]
============================
Example
//2D Multi Type Array
var myarray2: (string | number)[][]=[ [10, "xyz"], ["abc",100]];
console.log(myarray2);
Output
[[10, 'xyz' ], [ 'abc', 100]]
Access Array Elements
Example
//2D Multi Type Array
var myarray2: (string | number) () ()=( [10, "xyz"], ["abc",100]];
console.log(myarray2);
//Access 2D array elements
console.log(myarray2[0][0]);
console.log(myarray2[0][1]);
console.log(myarray2[1][0]);
console.log(myarray2[1][1]);
Output
10
xyz
abc
100
loop to access array elements
console.log("Reading data from array using for loop");for(var i=0;i<myarray2.length;i++){for(var j=0;j<myarray2[i].length;j++){console.log(myarray2[i][j]);}}
Output
10
xyz
abc
100
loop to access array elements
console.log("Reading data from array using for loop with in operator....for(var i in myarray2) //1 row{for(var j in myarray2[i]){console.log(myarray2[i][j]);}}
Output
10
xyz
abc
100
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);
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"]
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
========================
- 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];
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.
Types of Functions
1. Named Functions
A named function is one where you declare and call a function by its given name.
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
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.
Anonymous Function
var greeting=function(){
console.log("Welcome to Typescript");
}
greeting(); //Welcome to Typescript
Anonymous Function include 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
(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!
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
-
You can declare multiple function signatures.
-
You must provide one implementation that handles all cases.
-
The implementation must be compatible with all declared signatures.
-
Unlike Java, return type alone cannot distinguish overloads.
Overloading can happen in two ways in TypeScript:
-
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]
.
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
// 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
-
Each TypeScript file can be a module.
-
Use
export
to make variables, functions, or classes available outside. -
Use
import
to bring them into another file. -
Supports named exports and default exports.
-
Helps in writing modular, reusable, and maintainable code.