TypeScript Tutorial
Best Free TypeScript Training Tutorial | Beginner To Advanced Level
Introduction to TypeScript
TypeScript is an improved version of JavaScript. It includes everything that JavaScript has, plus extra features like data types, interfaces, and enums.
These features help developers find mistakes while writing code instead of after running it.
TypeScript makes code easier to read, understand, and maintain, especially in large projects.
Before running, TypeScript code is converted into JavaScript because browsers and Node.js can only run JavaScript.
Installing TypeScript
Before TypeScript, you need to install Node.js on your system.
Step 1: Install Node.js
- Visit the official Node.js website:
- Download the LTS (Long-Term Support) version.
- Run the installer and complete the installation.
Verify the Installation
Open Command Prompt or Terminal and run:
node -v
Check the npm version:
npm -v
Step 2: Install TypeScript
Install TypeScript globally using npm:
npm install -g typescript
What does this command mean?
npm→ Node Package Managerinstall→ Installs a package-g→ Installs the package globally, so it can be used from any foldertypescript→ The TypeScript package
Step 3: Verify TypeScript Installation
tsc -v
Write Your First TypeScript Program
Create a file named: hello.ts
console.log("Hi Kapoor");
let message: string = "Hello Kapoor";
console.log(message);Variables in Typescripts
Variables in TypeScript are used to store data. In other words, variables are containers that hold data values.
Types of Variable Declarations
In TypeScript, variables can be declared using three keywords: let, const, and var. Each keyword has its own scope and behavior.
// Explicit typing
const username: string = "Kapoor";
let count: number = 10;
let isCompleted: boolean = false;
// Type Inference (TypeScript automatically detects 'string')
let city = "Noida";const: Block-scoped constant (cannot be reassigned). Use by default.
let: Block-scoped variable (can be reassigned).
var: Function-scoped variable (avoid in modern TypeScript).
1. let
The let keyword allows you to declare block-scoped variables. This means that the variable is only accessible within the block in which it was defined (such as within a function or an if statement).
let x: number = 10;
if (true) {
let x: number = 20; // Different x
console.log(x); // Output: 20
}
console.log(x); // Output: 10In this example, the first x is defined outside the block and retains its value, while the x inside the block shadows the outer variable.
2. const
The const keyword is used to declare variables that are read-only, meaning their values cannot be reassigned after their initial definition. Similar to let, const variables are block-scoped.
const PI: number = 3.14;
// PI = 3.14159; // This will cause an error: Cannot assign to 'PI'
console.log(PI); // Output: 3.14Here, attempting to reassign a new value to PI will result in a compile-time error.
3. var
The var keyword declares variables that are function-scoped or globally scoped, which can lead to unexpected behaviors due to hoisting. Hoisting means that variable declarations are moved to the top of their containing scope during compilation.
function example() {
if (true) {
var y: number = 30; // y is function-scoped
}
console.log(y); // Output: 30
}
example();
In this case, the variable y is accessible outside the if block because it is function-scoped.
Note: Rules for Variable Names
- Can contain letters, digits, `_`, and `$`.
- Cannot begin with a digit.
- Are case-sensitive.
- Cannot use reserved keywords.
Data Types in TypeScript
Data types define the kind of values a variable can store. TypeScript uses static typing to improve code safety and readability.
1. Primitive Types
The foundational types inherited directly from JavaScript:
string: Textual data ("Hello",'Playwright',`automation`).number: Numeric values, including integers, floating points, hex, and binary (42,3.14,0xFF).boolean: Logical true/false (true,false).null: Intentional absence of any object value.undefined: Variables that have been declared but not initialized.symbol: Unique and immutable primitive values used as object keys.bigint: Large integers that exceed standard number precision (9007199254740991n).
const testName: string = "Logic Nextgen Kapoor";
let timeout: number = 5000;
let isPassed: boolean = true;2. Object Data Types
Object types are more complex structures that can hold multiple values. Some common object types include:
Used to structure grouped data and collections:
- Arrays: Homogeneous lists of elements (
number[]orArray<string>). - Tuples: Fixed-length arrays where each element position has a specific type (
[string, number]). - Objects: Structured key-value pairs (
{ id: number; name: string }).
const tags: string[] = ["smoke", "regression"];
const responseStatus: [number, string] = [200, "OK"]; // Tuple1 Object
The object type represents a non-primitive type that can hold various properties.
let person: object = {
name: "kapoor",
age: 25
};2 Array
An Array in typescript can hold a collection of values of a specific type. You can define an array using the syntax type[] or Array<type>.
let numbers: number[] = [1, 2, 3, 4];
let strings: Array = ["apple", "banana", "cherry"];3 Tuple
A Tuple represents an array with a fixed number of elements, each of which can have a different type.
let tuple: [string, number] = ["Keshav", 30];3. Special Types
TypeScript provides special types to handle specific scenarios:
any: Opts out of type checking completely. Use sparingly.unknown: Type-safe counterpart toany. Must perform type checks before operating on the variable.void: Represents the absence of a return value (commonly used in functions).never: Represents values that never occur (e.g., functions that throw errors or never finish executing).
1 Any Type
The any type allows any value, effectively disabling type checking for that variable.
let variable: any = "Hello";
variable = 5; // Still valid2 Unknown
The unknown type is safer than any. You cannot perform operations on an unknown type until you perform type checking.
let value: unknown = 5;
// console.log(value.toFixed(2)); // Error: Object is of type 'unknown'3 Void
The void type is used for functions that do not return a value.
function logMessage(message: string): void {
console.log(message);
}4 Never
The never type represents a type that never occurs, such as a function that always throws an error.
function throwError(message: string): never {
throw new Error(message);
}Conditional statements – Simple if, if else, Ladder if else, Nested if else
Conditional statements allow your program to make decisions and execute specific blocks of code based on whether a condition evaluates to true or false.
1. Simple if
Executes a block of code only if the specified condition is true. If the condition is false, the code block is skipped entirely.
TypeScript
const isElementVisible: boolean = true;
if (isElementVisible) {
console.log("Clicking the element.");
}2.if else
Provides an alternative execution path. Executes the if block when the condition is true, and the else block when it is false.
TypeScript
const statusCode: number = 200;
if (statusCode === 200) {
console.log("Request successful.");
} else {
console.log("Request failed.");
}3. Ladder if else (Else-If Ladder)
Tests multiple conditions sequentially. It executes the block belonging to the first condition that evaluates to true. If none match, the final else block runs.
TypeScript
const 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("Grade: F");
}4. Nested if else Statement
An if or if...else statement placed inside another if or else block. Useful for checking secondary conditions after a primary condition passes.
TypeScript
const isLoggedIn: boolean = true;
const userRole: string = "admin";
if (isLoggedIn) {
console.log("User Mr. kapoor authenticated.");
// Nested check
if (userRole === "admin") {
console.log("Access granted to Admin Dashboard.");
} else {
console.log("Access granted to Standard User Dashboard.");
}
} else {
console.log("Access denied. Please log in first.");
}Loop
Loops in TypeScript execute a block of code repeatedly as long as a specified condition remains true. TypeScript supports all standard JavaScript loops and adds type safety when iterating over arrays, objects, and collections.
1. Traditional or Simple for Loop
Best when you know the exact number of iterations in advance.
TypeScript
for (let i = 0; i < 5; i++) {
console.log(i);
}2. for of Loop (Iterating Values)
Iterates directly over the values of an iterable object like an Array, String, Map, or Set.
TypeScript
const browsers: string[] = ["chromium", "firefox", "webkit"];
for (const browser of browsers) {
console.log(`Testing on: ${browser}`);
}
3. for in Loop (Iterating Keys)
Iterates over the enumerable keys/properties of an object or indices of an array.
TypeScript
const userRole = { admin: true, editor: false, viewer: false };
for (const role in userRole) {
console.log(`Role: ${role}`); // Outputs: admin, editor, viewer
}
4. while Loop
Executes as long as the condition is true. The condition is checked before entering the loop body.
TypeScript
let i = 0;
while (i < 5) {
console.log(i);
i++;
}5. do while Loop
Executes the code block at least once before checking the condition.
TypeScript
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);