TypeScript Complete Guide – From Beginner to Advanced
TypeScript is a strongly typed programming language built on top of JavaScript. It adds static typing, interfaces, classes, generics, and other features to JavaScript.
This guide covers TypeScript from basics to advanced concepts, with practical examples and expected outputs. It is especially useful for Playwright automation testing using JavaScript/TypeScript.
1. What is TypeScript?
TypeScript is a superset of JavaScript developed by Microsoft.
- JavaScript code can run in TypeScript projects.
- TypeScript supports static type checking.
- TypeScript helps identify errors during development.
- TypeScript code is compiled into JavaScript.
- Playwright supports TypeScript directly.
JavaScript vs TypeScript
| JavaScript | TypeScript |
|---|---|
| Dynamically typed | Statically typed |
| No compile-time type checking | Compile-time type checking |
Uses .js | Uses .ts |
| No built-in interfaces | Supports interfaces |
| Supports classes | Supports classes and access modifiers |
| Runtime errors may occur due to type mistakes | Many type mistakes can be caught before execution |
2. Install TypeScript
First, install Node.js. Then create a project.
mkdir typescript-demo
cd typescript-demo
npm init -y
npm install typescript --save-dev
Check the TypeScript version:
npx tsc --version
Example output:
Version 5.x.x
Create a TypeScript file:
app.ts
let message: string = "Hello TypeScript";
console.log(message);
Compile the TypeScript file:
npx tsc app.ts
Run the generated JavaScript:
node app.js
Output:
Hello TypeScript
3. TypeScript Data Types
TypeScript supports several built-in data types.
3.1 String
let firstName: string = "Sumit";
console.log(firstName);
console.log(typeof firstName);
Output:
Sumit
string
3.2 Number
let age: number = 35;
let salary: number = 25000.50;
console.log(age);
console.log(salary);
Output:
35
25000.5
3.3 Boolean
let isActive: boolean = true;
let isCompleted: boolean = false;
console.log(isActive);
console.log(isCompleted);
Output:
true
false
3.4 Array
There are two ways to declare arrays.
let numbers: number[] = [10, 20, 30, 40];
let names: Array<string> = [
"Sumit",
"Rahul",
"Amit"
];
console.log(numbers);
console.log(names);
Output:
[ 10, 20, 30, 40 ]
[ 'Sumit', 'Rahul', 'Amit' ]
3.5 Tuple
A tuple allows you to define fixed types for elements at specific positions.
let employee: [number, string, number] =
[101, "Sumit", 50000];
console.log(employee);
console.log(employee[0]);
console.log(employee[1]);
console.log(employee[2]);
Output:
[ 101, 'Sumit', 50000 ]
101
Sumit
50000
3.6 Any
The any type disables most type checking for a variable.
let data: any = 100;
console.log(data);
data = "Hello";
console.log(data);
data = true;
console.log(data);
Output:
100
Hello
true
Avoid using any unnecessarily because it removes TypeScript's type safety.
3.7 Unknown
unknown is safer than any. You must check the type before performing operations that require a specific type.
let value: unknown = "TypeScript";
if (typeof value === "string") {
console.log(value.toUpperCase());
}
Output:
TYPESCRIPT
3.8 Void
The void type is commonly used for functions that do not return a value.
function greet(): void {
console.log("Welcome to TypeScript");
}
greet();
Output:
Welcome to TypeScript
3.9 Null and Undefined
let username: null = null;
let userAge: undefined = undefined;
console.log(username);
console.log(userAge);
Output:
null
undefined
3.10 Never
The never type represents values that never occur, such as a function that always throws an error.
function throwError(): never {
throw new Error("Something went wrong");
}
throwError();
Output:
Error: Something went wrong
4. Type Inference
TypeScript can automatically identify the data type based on the assigned value.
let employeeName = "Sumit";
let employeeAge = 35;
let isPermanent = true;
console.log(employeeName);
console.log(employeeAge);
console.log(isPermanent);
Output:
Sumit
35
true
TypeScript infers:
employeeName→ stringemployeeAge→ numberisPermanent→ boolean
5. Variables – let, const and var
var company = "FedEx";
let employee = "Sumit";
const country = "India";
console.log(company);
console.log(employee);
console.log(country);
Output:
FedEx
Sumit
India
| Keyword | Scope | Reassignment |
|---|---|---|
| var | Function | Yes |
| let | Block | Yes |
| const | Block | No |
Best practice: Use const by default and let when reassignment is required.
6. Operators in TypeScript
Arithmetic Operators
let a: number = 20;
let b: number = 10;
console.log(a + b);
console.log(a - b);
console.log(a * b);
console.log(a / b);
console.log(a % b);
Output:
30
10
200
2
0
Comparison Operators
let x = 10;
let y = 20;
console.log(x > y);
console.log(x < y);
console.log(x == y);
console.log(x === y);
console.log(x != y);
Output:
false
true
false
false
true
Logical Operators
let age = 25;
let hasLicense = true;
console.log(age >= 18 && hasLicense);
console.log(age < 18 || hasLicense);
console.log(!hasLicense);
Output:
true
true
false
7. Conditional Statements
If-Else
let marks: number = 75;
if (marks >= 90) {
console.log("Grade A");
} else if (marks >= 60) {
console.log("Grade B");
} else {
console.log("Grade C");
}
Output:
Grade B
Switch Statement
let browser: string = "Chrome";
switch (browser) {
case "Chrome":
console.log("Chrome browser selected");
break;
case "Firefox":
console.log("Firefox browser selected");
break;
case "Edge":
console.log("Edge browser selected");
break;
default:
console.log("Invalid browser");
}
Output:
Chrome browser selected
8. Loops in TypeScript
For Loop
for (let i = 1; i <= 5; i++) {
console.log(i);
}
Output:
1
2
3
4
5
While Loop
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
Output:
1
2
3
4
5
Do-While Loop
let i = 1;
do {
console.log(i);
i++;
} while (i <= 3);
Output:
1
2
3
For-Of Loop
Used to iterate over array values.
let browsers: string[] = [
"Chrome",
"Firefox",
"Edge"
];
for (let browser of browsers) {
console.log(browser);
}
Output:
Chrome
Firefox
Edge
For-In Loop
Used to iterate over object keys or array indexes.
let employee = {
id: 101,
name: "Sumit",
salary: 50000
};
for (let key in employee) {
console.log(key);
}
Output:
id
name
salary
9. Functions in TypeScript
Functions are reusable blocks of code.
9.1 Simple Function
function greet(): void {
console.log("Hello Sumit");
}
greet();
Output:
Hello Sumit
9.2 Function with Parameters
function add(a: number, b: number): number {
return a + b;
}
let result = add(10, 20);
console.log(result);
Output:
30
9.3 Optional Parameters
Use ? to make a parameter optional.
function employeeDetails(
name: string,
age?: number
): void {
console.log("Name:", name);
console.log("Age:", age);
}
employeeDetails("Sumit");
employeeDetails("Rahul", 30);
Output:
Name: Sumit
Age: undefined
Name: Rahul
Age: 30
9.4 Default Parameters
function login(
username: string,
role: string = "Tester"
): void {
console.log(username);
console.log(role);
}
login("Sumit");
login("Rahul", "Admin");
Output:
Sumit
Tester
Rahul
Admin
9.5 Rest Parameters
Rest parameters allow a function to accept multiple arguments.
function sum(...numbers: number[]): number {
return numbers.reduce(
(total, value) => total + value,
0
);
}
console.log(sum(10, 20, 30));
console.log(sum(5, 10, 15, 20));
Output:
60
50
9.6 Arrow Functions
Arrow functions provide a shorter syntax.
const multiply = (a: number, b: number): number => {
return a * b;
};
console.log(multiply(5, 4));
Output:
20
Shorter version:
const square = (num: number): number => num * num;
console.log(square(5));
Output:
25
9.7 Anonymous Functions
let message = function(): void {
console.log("Anonymous Function");
};
message();
Output:
Anonymous Function
9.8 Function Overloading
Function overloading allows multiple function signatures for different parameter combinations.
function display(value: string): void;
function display(value: number): void;
function display(value: string | number): void {
console.log(value);
}
display("Hello");
display(100);
Output:
Hello
100
10. Type Aliases
A type alias allows you to create a custom type.
type Employee = {
id: number;
name: string;
salary: number;
};
let emp1: Employee = {
id: 101,
name: "Sumit",
salary: 50000
};
console.log(emp1);
Output:
{ id: 101, name: 'Sumit', salary: 50000 }
You can reuse the same type for multiple objects.
let emp2: Employee = {
id: 102,
name: "Rahul",
salary: 60000
};
console.log(emp2.name);
Output:
Rahul
11. Interfaces in TypeScript
An interface defines the structure of an object.
interface Employee {
id: number;
name: string;
salary: number;
}
let emp: Employee = {
id: 101,
name: "Sumit",
salary: 50000
};
console.log(emp.id);
console.log(emp.name);
console.log(emp.salary);
Output:
101
Sumit
50000
11.1 Optional Properties
Use ? for optional properties.
interface User {
id: number;
name: string;
email?: string;
}
let user: User = {
id: 101,
name: "Sumit"
};
console.log(user);
Output:
{ id: 101, name: 'Sumit' }
11.2 Readonly Properties
A readonly property cannot be reassigned after object creation.
interface Employee {
readonly id: number;
name: string;
}
let emp: Employee = {
id: 101,
name: "Sumit"
};
emp.name = "Rahul";
console.log(emp);
Output:
{ id: 101, name: 'Rahul' }
The following would produce a TypeScript compilation error:
emp.id = 102;
11.3 Interface with Methods
interface Calculator {
add(a: number, b: number): number;
}
let calc: Calculator = {
add(a, b) {
return a + b;
}
};
console.log(calc.add(10, 20));
Output:
30
11.4 Interface Inheritance
Use extends to inherit properties from another interface.
interface Person {
name: string;
age: number;
}
interface Employee extends Person {
employeeId: number;
salary: number;
}
let emp: Employee = {
name: "Sumit",
age: 35,
employeeId: 101,
salary: 50000
};
console.log(emp);
Output:
{
name: 'Sumit',
age: 35,
employeeId: 101,
salary: 50000
}
12. Union and Intersection Types
12.1 Union Types
A union allows a variable to accept multiple types.
let id: string | number;
id = 101;
console.log(id);
id = "EMP101";
console.log(id);
Output:
101
EMP101
Another example:
function printValue(value: string | number): void {
if (typeof value === "string") {
console.log(value.toUpperCase());
} else {
console.log(value * 2);
}
}
printValue("hello");
printValue(20);
Output:
HELLO
40
12.2 Intersection Types
An intersection combines multiple types into one.
type Person = {
name: string;
};
type Employee = {
salary: number;
};
type EmployeeDetails = Person & Employee;
let emp: EmployeeDetails = {
name: "Sumit",
salary: 50000
};
console.log(emp);
Output:
{ name: 'Sumit', salary: 50000 }
13. Enum in TypeScript
Enums define a collection of named constants.
Numeric Enum
enum Status {
Pending,
Running,
Completed,
Failed
}
console.log(Status.Pending);
console.log(Status.Running);
console.log(Status.Completed);
console.log(Status.Failed);
Output:
0
1
2
3
String Enum
enum Browser {
Chrome = "CHROME",
Firefox = "FIREFOX",
Edge = "EDGE"
}
console.log(Browser.Chrome);
console.log(Browser.Firefox);
Output:
CHROME
FIREFOX
Example for automation testing:
enum TestStatus {
PASS = "PASS",
FAIL = "FAIL",
SKIP = "SKIP"
}
let status: TestStatus = TestStatus.PASS;
console.log(status);
Output:
PASS
14. Classes in TypeScript
Classes are blueprints for creating objects.
class Employee {
id: number;
name: string;
salary: number;
constructor(id: number, name: string, salary: number) {
this.id = id;
this.name = name;
this.salary = salary;
}
display(): void {
console.log(this.id);
console.log(this.name);
console.log(this.salary);
}
}
let emp = new Employee(101, "Sumit", 50000);
emp.display();
Output:
101
Sumit
50000
14.1 Constructor
A constructor initializes class properties when an object is created.
class Student {
constructor(
public name: string,
public age: number
) {}
display(): void {
console.log(this.name, this.age);
}
}
let student = new Student("Sumit", 35);
student.display();
Output:
Sumit 35
14.2 Access Modifiers
TypeScript supports three primary access modifiers.
| Modifier | Accessibility |
|---|---|
| public | Accessible everywhere |
| private | Accessible only inside the class |
| protected | Accessible inside the class and subclasses |
Example:
class Employee {
public name: string;
private salary: number;
protected department: string;
constructor(
name: string,
salary: number,
department: string
) {
this.name = name;
this.salary = salary;
this.department = department;
}
display(): void {
console.log(this.name);
console.log(this.salary);
console.log(this.department);
}
}
let emp = new Employee("Sumit", 50000, "QA");
emp.display();
Output:
Sumit
50000
QA
Accessing emp.salary directly outside the class produces a TypeScript error.
14.3 Inheritance
Inheritance allows one class to reuse another class's properties and methods.
class Animal {
eat(): void {
console.log("Animal is eating");
}
}
class Dog extends Animal {
bark(): void {
console.log("Dog is barking");
}
}
let dog = new Dog();
dog.eat();
dog.bark();
Output:
Animal is eating
Dog is barking
14.4 Method Overriding
class Animal {
sound(): void {
console.log("Animal makes sound");
}
}
class Dog extends Animal {
override sound(): void {
console.log("Dog barks");
}
}
let dog = new Dog();
dog.sound();
Output:
Dog barks
14.5 Static Properties and Methods
Static members belong to the class instead of individual objects.
class MathUtil {
static PI: number = 3.14;
static square(num: number): number {
return num * num;
}
}
console.log(MathUtil.PI);
console.log(MathUtil.square(5));
Output:
3.14
25
14.6 Abstract Classes
An abstract class cannot be instantiated directly. It can be extended by another class.
abstract class Vehicle {
abstract start(): void;
stop(): void {
console.log("Vehicle stopped");
}
}
class Car extends Vehicle {
start(): void {
console.log("Car started");
}
}
let car = new Car();
car.start();
car.stop();
Output:
Car started
Vehicle stopped
15. Arrays in TypeScript
Arrays store multiple values of the same type or a specified combination of types.
let numbers: number[] = [10, 20, 30, 40, 50];
console.log(numbers.length);
console.log(numbers[0]);
console.log(numbers[2]);
Output:
5
10
30
15.1 Push and Pop
let fruits: string[] = ["Apple", "Banana"];
fruits.push("Mango");
console.log(fruits);
fruits.pop();
console.log(fruits);
Output:
[ 'Apple', 'Banana', 'Mango' ]
[ 'Apple', 'Banana' ]
15.2 Map
Transforms every array element and returns a new array.
let numbers = [1, 2, 3, 4];
let result = numbers.map(num => num * 2);
console.log(result);
Output:
[ 2, 4, 6, 8 ]
15.3 Filter
Returns elements that satisfy a condition.
let numbers = [10, 15, 20, 25, 30];
let result = numbers.filter(num => num > 20);
console.log(result);
Output:
[ 25, 30 ]
15.4 Reduce
Reduces an array to a single value.
let numbers = [10, 20, 30, 40];
let total = numbers.reduce(
(sum, num) => sum + num,
0
);
console.log(total);
Output:
100
15.5 Find
Returns the first element matching a condition.
let numbers = [10, 20, 30, 40];
let result = numbers.find(num => num > 20);
console.log(result);
Output:
30
15.6 Some and Every
let numbers = [10, 20, 30, 40];
console.log(numbers.some(num => num > 30));
console.log(numbers.every(num => num > 5));
Output:
true
true
15.7 Sort
let numbers = [50, 10, 40, 20, 30];
numbers.sort((a, b) => a - b);
console.log(numbers);
Output:
[ 10, 20, 30, 40, 50 ]
For descending order:
numbers.sort((a, b) => b - a);
console.log(numbers);
Output:
[ 50, 40, 30, 20, 10 ]
15.8 Array of Objects
This is particularly useful in automation frameworks.
interface Employee {
id: number;
name: string;
salary: number;
}
let employees: Employee[] = [
{ id: 101, name: "Sumit", salary: 50000 },
{ id: 102, name: "Rahul", salary: 60000 },
{ id: 103, name: "Amit", salary: 40000 }
];
employees.forEach(emp => {
console.log(emp.id, emp.name, emp.salary);
});
Output:
101 Sumit 50000
102 Rahul 60000
103 Amit 40000
Sort employees by salary:
employees.sort((a, b) => a.salary - b.salary);
console.log(employees);
Output:
[
{ id: 103, name: 'Amit', salary: 40000 },
{ id: 101, name: 'Sumit', salary: 50000 },
{ id: 102, name: 'Rahul', salary: 60000 }
]
16. Objects in TypeScript
Objects store data as key-value pairs.
let employee = {
id: 101,
name: "Sumit",
salary: 50000,
department: "QA"
};
console.log(employee.id);
console.log(employee.name);
console.log(employee.salary);
console.log(employee.department);
Output:
101
Sumit
50000
QA
Object Destructuring
let employee = {
id: 101,
name: "Sumit",
salary: 50000
};
let { id, name, salary } = employee;
console.log(id);
console.log(name);
console.log(salary);
Output:
101
Sumit
50000
Spread Operator
let employee = {
id: 101,
name: "Sumit"
};
let updatedEmployee = {
...employee,
salary: 50000
};
console.log(updatedEmployee);
Output:
{ id: 101, name: 'Sumit', salary: 50000 }
17. Generics in TypeScript
Generics allow you to create reusable functions, interfaces, and classes that work with different data types while preserving type safety.
17.1 Generic Function
function display<T>(value: T): T {
return value;
}
console.log(display<string>("Hello"));
console.log(display<number>(100));
console.log(display<boolean>(true));
Output:
Hello
100
true
Here, T represents a type parameter.
17.2 Generic Array
function getFirstElement<T>(items: T[]): T {
return items[0];
}
console.log(getFirstElement<number>([10, 20, 30]));
console.log(getFirstElement<string>([
"Chrome",
"Firefox"
]));
Output:
10
Chrome
17.3 Generic Interface
interface ApiResponse<T> {
status: number;
message: string;
data: T;
}
interface User {
id: number;
name: string;
}
let response: ApiResponse<User> = {
status: 200,
message: "Success",
data: {
id: 101,
name: "Sumit"
}
};
console.log(response.data.name);
Output:
Sumit
17.4 Generic Class
class Storage<T> {
private value: T;
constructor(value: T) {
this.value = value;
}
getValue(): T {
return this.value;
}
}
let numberStorage = new Storage<number>(100);
let stringStorage = new Storage<string>("Hello");
console.log(numberStorage.getValue());
console.log(stringStorage.getValue());
Output:
100
Hello
18. Type Assertions
Type assertions tell TypeScript that you know the type of a value.
let value: unknown = "Hello TypeScript";
let result = (value as string).toUpperCase();
console.log(result);
Output:
HELLO TYPESCRIPT
Another syntax:
let message: unknown = "Welcome";
let result = (<string>message).toUpperCase();
console.log(result);
Output:
WELCOME
Type assertions do not convert values at runtime. They only affect compile-time type checking.
19. Type Narrowing
Type narrowing means checking a variable's type before using it.
function printData(value: string | number): void {
if (typeof value === "string") {
console.log("String:", value.toUpperCase());
} else {
console.log("Number:", value.toFixed(2));
}
}
printData("typescript");
printData(125.5);
Output:
String: TYPESCRIPT
Number: 125.50
Common narrowing techniques:
typeofinstanceofin- Equality checks
- Custom type guards
Custom Type Guard
interface Dog {
bark(): void;
}
interface Cat {
meow(): void;
}
function isDog(value: Dog | Cat): value is Dog {
return "bark" in value;
}
let pet: Dog | Cat = {
bark() {
console.log("Woof");
}
};
if (isDog(pet)) {
pet.bark();
}
Output:
Woof
20. Utility Types
TypeScript provides built-in utility types for transforming existing types.
Consider this interface:
interface Employee {
id: number;
name: string;
email: string;
salary: number;
}
Partial
Makes all properties optional.
let emp: Partial<Employee> = {
name: "Sumit"
};
console.log(emp);
Output:
{ name: 'Sumit' }
Required
Makes all properties required.
type RequiredEmployee = Required<Employee>;
Readonly
Makes all properties readonly.
type ReadonlyEmployee = Readonly<Employee>;
Pick
Selects specific properties.
type EmployeeSummary = Pick<Employee, "id" | "name">;
let emp: EmployeeSummary = {
id: 101,
name: "Sumit"
};
console.log(emp);
Output:
{ id: 101, name: 'Sumit' }
Omit
Excludes specific properties.
type EmployeeWithoutSalary = Omit<Employee, "salary">;
let emp: EmployeeWithoutSalary = {
id: 101,
name: "Sumit",
email: "sumit@example.com"
};
console.log(emp);
Output:
{
id: 101,
name: 'Sumit',
email: 'sumit@example.com'
}
Record
Creates an object type with specified keys and values.
type BrowserStatus = Record<string, boolean>;
let browsers: BrowserStatus = {
Chrome: true,
Firefox: false,
Edge: true
};
console.log(browsers);
Output:
{ Chrome: true, Firefox: false, Edge: true }
21. Modules and Exports
Modules allow you to divide your application into multiple files.
math.ts
export function add(a: number, b: number): number {
return a + b;
}
export function multiply(a: number, b: number): number {
return a * b;
}
main.ts
import { add, multiply } from "./math";
console.log(add(10, 20));
console.log(multiply(5, 4));
Output:
30
20
Default Export
user.ts
export default class User {
constructor(public name: string) {}
display(): void {
console.log(this.name);
}
}
main.ts
import User from "./user";
let user = new User("Sumit");
user.display();
Output:
Sumit
22. Asynchronous Programming
Asynchronous programming is important for API testing and Playwright automation.
22.1 Promise
A Promise represents the eventual completion or failure of an asynchronous operation.
function getData(): Promise<string> {
return new Promise((resolve) => {
resolve("Data received successfully");
});
}
getData().then(result => {
console.log(result);
});
Output:
Data received successfully
22.2 Async and Await
function getUser(): Promise<string> {
return new Promise(resolve => {
resolve("Sumit");
});
}
async function displayUser(): Promise<void> {
let user = await getUser();
console.log(user);
}
displayUser();
Output:
Sumit
22.3 Try-Catch
async function getData(): Promise<void> {
try {
throw new Error("API request failed");
} catch (error) {
if (error instanceof Error) {
console.log(error.message);
}
}
}
getData();
Output:
API request failed
23. Exception Handling
Use try, catch, and finally to handle runtime exceptions.
try {
let result = 10 / 0;
if (!Number.isFinite(result)) {
throw new Error("Invalid calculation");
}
console.log(result);
} catch (error) {
if (error instanceof Error) {
console.log(error.message);
}
} finally {
console.log("Execution completed");
}
Output:
Invalid calculation
Execution completed
24. Map and Set
Map
Map stores key-value pairs.
let employeeMap = new Map<number, string>();
employeeMap.set(101, "Sumit");
employeeMap.set(102, "Rahul");
employeeMap.set(103, "Amit");
console.log(employeeMap.get(101));
console.log(employeeMap.size);
console.log(employeeMap.has(102));
Output:
Sumit
3
true
Iterating Map:
for (let [id, name] of employeeMap) {
console.log(id, name);
}
Output:
101 Sumit
102 Rahul
103 Amit
Set
Set stores unique values.
let numbers = new Set<number>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(10);
console.log(numbers);
console.log(numbers.size);
Output:
Set(3) { 10, 20, 30 }
3
25. String Methods
let message: string = "Welcome to TypeScript";
console.log(message.length);
console.log(message.toUpperCase());
console.log(message.toLowerCase());
console.log(message.includes("TypeScript"));
console.log(message.startsWith("Welcome"));
console.log(message.substring(0, 7));
console.log(message.replace("TypeScript", "Playwright"));
Output:
21
WELCOME TO TYPESCRIPT
welcome to typescript
true
true
Welcome
Welcome to Playwright
26. TypeScript File Handling and JSON
JSON is commonly used in API testing and automation.
Convert Object to JSON
let employee = {
id: 101,
name: "Sumit",
salary: 50000
};
let jsonData = JSON.stringify(employee);
console.log(jsonData);
Output:
{"id":101,"name":"Sumit","salary":50000}
Convert JSON to Object
let jsonString = '{"id":101,"name":"Sumit"}';
let employee = JSON.parse(jsonString);
console.log(employee.id);
console.log(employee.name);
Output:
101
Sumit
For real API responses, validate or type-check parsed JSON because JSON.parse() does not guarantee that the data matches your TypeScript interface.
27. TypeScript Generators
Generators are functions that can pause and resume execution using yield.
function* generateNumbers() {
yield 10;
yield 20;
yield 30;
}
let result = generateNumbers();
console.log(result.next().value);
console.log(result.next().value);
console.log(result.next().value);
Output:
10
20
30
28. TypeScript Decorators
Decorators are functions that can modify or annotate classes and class members. They are used in frameworks such as Angular and other TypeScript libraries.
Example using a standard class decorator:
function Logger(
target: Function,
context: ClassDecoratorContext
) {
console.log("Class decorator executed:", context.name);
}
@Logger
class Employee {
name = "Sumit";
}
let emp = new Employee();
console.log(emp.name);
Output:
Class decorator executed: Employee
Sumit
This example uses the modern decorator model. TypeScript also supports the older experimental decorator model through experimentalDecorators, which has different signatures.
29. TypeScript Configuration – tsconfig.json
The tsconfig.json file defines how TypeScript compiles your project.
Create it using:
npx tsc --init
Example configuration:
{
"compilerOptions": {
"target": "ES2022",
"module": "CommonJS",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"outDir": "./dist",
"rootDir": "./src"
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules"]
}
Important compiler options:
| Option | Description |
|---|---|
| target | JavaScript version to generate |
| module | Module system |
| strict | Enables strict type checking |
| esModuleInterop | Improves CommonJS interoperability |
| outDir | Output directory |
| rootDir | Source directory |
| skipLibCheck | Skips declaration-file checking |
| noImplicitAny | Reports implicit any types |
| strictNullChecks | Checks null and undefined |
| sourceMap | Generates source maps |
Compile the complete project:
npx tsc
Watch for file changes:
npx tsc --watch
30. TypeScript Project Structure
A recommended basic project structure:
typescript-demo/
│
├── src/
│ ├── index.ts
│ ├── employee.ts
│ ├── math.ts
│ │
│ └── models/
│ └── user.ts
│
├── dist/
│
├── package.json
├── tsconfig.json
└── node_modules/
Run the compiled application:
node dist/index.js
31. TypeScript with Playwright Automation
One of the most important applications of TypeScript is browser automation using Playwright.
Install Playwright:
npm init playwright@latest
Select:
- TypeScript
- Tests directory:
tests - GitHub Actions: Yes (optional)
- Install browsers: Yes
Example project structure:
playwright-typescript/
│
├── tests/
│ ├── login.spec.ts
│ ├── home.spec.ts
│ └── api.spec.ts
│
├── playwright.config.ts
├── package.json
└── tsconfig.json
31.1 First Playwright Test
login.spec.ts
import { test, expect } from '@playwright/test';
test('Verify page title', async ({ page }) => {
await page.goto('https://playwright.dev');
await expect(page).toHaveTitle(/Playwright/);
console.log("Title validation successful");
});
Run:
npx playwright test
Expected output (assuming the test passes):
Running 1 test using 1 worker
✓ tests/login.spec.ts
1 passed
31.2 Locators
import { test, expect } from '@playwright/test';
test('Verify locators', async ({ page }) => {
await page.goto('https://example.com');
let heading = page.locator('h1');
await expect(heading).toHaveText('Example Domain');
console.log(await heading.textContent());
});
Output:
Example Domain
Common Playwright locators:
| Locator | Example |
|---|---|
| getByRole | page.getByRole('button') |
| getByText | page.getByText('Login') |
| getByLabel | page.getByLabel('Username') |
| getByPlaceholder | page.getByPlaceholder('Enter email') |
| getByTestId | page.getByTestId('login-btn') |
| locator | page.locator('#username') |
31.3 Playwright Assertions
import { test, expect } from '@playwright/test';
test('Assertion example', async ({ page }) => {
await page.goto('https://example.com');
await expect(page).toHaveURL(/example.com/);
await expect(page.locator('h1')).toBeVisible();
await expect(page.locator('h1')).toHaveText('Example Domain');
});
Common assertions:
await expect(locator).toBeVisible();
await expect(locator).toBeHidden();
await expect(locator).toBeEnabled();
await expect(locator).toBeDisabled();
await expect(locator).toHaveText('Login');
await expect(locator).toContainText('Welcome');
await expect(locator).toHaveValue('Sumit');
await expect(locator).toHaveAttribute('type', 'text');
await expect(page).toHaveTitle('Example Domain');
31.4 Handling Dropdowns
await page.locator('#country').selectOption('India');
31.5 Handling Alerts
page.on('dialog', async dialog => {
console.log(dialog.message());
await dialog.accept();
});
await page.locator('#alertButton').click();
31.6 Handling Frames
let frame = page.frameLocator('#myFrame');
await frame.locator('#username').fill('Sumit');
await frame.locator('#password').fill('12345');
31.7 API Testing with TypeScript
Playwright also provides an API testing interface.
import { test, expect } from '@playwright/test';
test('Verify API GET request', async ({ request }) => {
const response = await request.get(
'https://jsonplaceholder.typicode.com/users/1'
);
expect(response.status()).toBe(200);
const responseBody = await response.json();
console.log(responseBody.name);
expect(responseBody.id).toBe(1);
});
Expected output:
Leanne Graham
31.8 API POST Request
import { test, expect } from '@playwright/test';
test('Create user', async ({ request }) => {
const response = await request.post(
'https://jsonplaceholder.typicode.com/posts',
{
data: {
title: 'TypeScript',
body: 'Playwright API Testing',
userId: 1
}
}
);
expect(response.status()).toBe(201);
const responseBody = await response.json();
console.log(responseBody);
});
Expected output (representative):
{
"title": "TypeScript",
"body": "Playwright API Testing",
"userId": 1,
"id": 101
}
32. TypeScript with Page Object Model (POM)
Page Object Model is a design pattern used to separate page locators and actions from test cases.
loginPage.ts
import { Page, Locator } from '@playwright/test';
export class LoginPage {
readonly page: Page;
readonly username: Locator;
readonly password: Locator;
readonly loginButton: Locator;
constructor(page: Page) {
this.page = page;
this.username = page.locator('#username');
this.password = page.locator('#password');
this.loginButton = page.locator('#login');
}
async login(
username: string,
password: string
): Promise<void> {
await this.username.fill(username);
await this.password.fill(password);
await this.loginButton.click();
}
}
login.spec.ts
import { test, expect } from '@playwright/test';
import { LoginPage } from './loginPage';
test('Login test', async ({ page }) => {
const loginPage = new LoginPage(page);
await page.goto('https://example.com/login');
await loginPage.login('Sumit', 'password123');
console.log("Login executed");
});
Expected output (assuming the example application and credentials are valid):
Login executed
1 passed
33. TypeScript Fixtures
Fixtures provide reusable test setup and teardown functionality.
import {
test as base,
expect
} from '@playwright/test';
type MyFixtures = {
employeeName: string;
};
export const test = base.extend<MyFixtures>({
employeeName: async ({}, use) => {
await use("Sumit");
}
});
export { expect };
test.spec.ts
import { test, expect } from './fixtures';
test('Fixture example', async ({ employeeName }) => {
console.log(employeeName);
expect(employeeName).toBe("Sumit");
});
Output:
Sumit
1 passed
34. TypeScript with API Response Interfaces
This is particularly useful for validating complex API responses.
interface User {
id: number;
name: string;
email: string;
}
async function getUser(): Promise<User> {
return {
id: 101,
name: "Sumit",
email: "sumit@example.com"
};
}
async function main(): Promise<void> {
const user = await getUser();
console.log(user.id);
console.log(user.name);
console.log(user.email);
}
main();
Output:
101
Sumit
sumit@example.com
Remember: An interface provides compile-time checking, not automatic runtime validation of external API responses.
35. Important TypeScript Interview Questions
These are useful topics for automation tester interviews.
| No. | Interview question |
|---|---|
| 1 | What is TypeScript? |
| 2 | Difference between JavaScript and TypeScript? |
| 3 | What is type inference? |
| 4 | Difference between any and unknown? |
| 5 | Difference between interface and type? |
| 6 | What are union and intersection types? |
| 7 | What are generics? |
| 8 | What is an enum? |
| 9 | What is type assertion? |
| 10 | What is type narrowing? |
| 11 | What are access modifiers? |
| 12 | What is inheritance? |
| 13 | What is an abstract class? |
| 14 | What are optional parameters? |
| 15 | What are readonly properties? |
| 16 | What is the difference between let, const, and var? |
| 17 | What is a Promise? |
| 18 | What is async/await? |
| 19 | What is a decorator? |
| 20 | What are utility types? |
| 21 | What is tsconfig.json? |
| 22 | What is the difference between map() and filter()? |
| 23 | What is the difference between find() and some()? |
| 24 | What are modules and exports? |
| 25 | How do you use TypeScript with Playwright? |
36. JavaScript vs TypeScript for Automation Testing
| Feature | JavaScript | TypeScript |
|---|---|---|
| Variable declaration | Yes | Yes |
| Static typing | No | Yes |
| Interface | No | Yes |
| Type aliases | No | Yes |
| Generics | No | Yes |
| Classes | Yes | Yes |
| Async/await | Yes | Yes |
| Playwright support | Yes | Yes |
| Compile-time checking | No | Yes |
| IDE autocomplete | Available | Improved with types |
Recommendation: For large Playwright automation frameworks, TypeScript is an excellent choice because it improves maintainability, reusable components, API response handling, and compile-time error detection.
37. Practical TypeScript Programs for Practice
Try implementing these programs without looking at the solutions.
- Reverse a string – Beginner
- Find duplicate numbers in an array – Beginner
- Find the second-largest number – Beginner
- Sort employee objects by salary – Intermediate
- Remove duplicate elements from an array – Intermediate
- Count character occurrences in a string – Intermediate
- Find the maximum salary using reduce() – Intermediate
- Create a generic reusable API response function – Advanced
- Create a custom Playwright fixture – Advanced
- Build a Page Object Model framework – Advanced
38. Recommended Learning Roadmap
-
Week 1 – TypeScript Fundamentals
Variables, data types, operators, conditions, loops, functions and arrays.
-
Week 2 – Object-Oriented Programming
Classes, interfaces, inheritance, abstraction, enums and access modifiers.
-
Week 3 – Advanced TypeScript
Generics, utility types, promises, async/await, modules and type narrowing.
-
Week 4 – Playwright Automation
Locators, assertions, fixtures, API testing, POM, configuration and CI/CD.
Official learning resources
- TypeScript Official Documentation
- TypeScript Playground
- Playwright Documentation
- TypeScript Compiler Configuration
My recommendation: Learn TypeScript fundamentals first, then focus on interfaces, classes, generics, array methods, async/await and fixtures. These concepts are particularly important when developing enterprise-level Playwright automation frameworks using TypeScript.

No comments:
Post a Comment