Typescript
1. What is TypeScript?
TypeScript is a superset of JavaScript that adds features such as static typing, interfaces, classes, access modifiers, generics, and type aliases. TypeScript code is converted to JavaScript before execution.
We write code in .ts files. TypeScript checks the code during development and converts it into JavaScript, which can then be executed by Node.js or a browser.
What is Static Typing?
Static typing means we specify what type of value a variable can contain.
let age: number = 30;
let name: string = “Manjiri”;
let isActive: boolean = true;
This is invalid:
age = “thirty”;
Because age is declared as a number.
Interview answer:
Static typing allows us to define the expected data type and helps identify type-related errors during development.
3. Basic Data Types
A variable is a named container used to store data, while a data type defines what kind of data that variable can hold, such as string, number, or boolean.
let browserName: string = “Chrome”;
let retryCount: number = 2;
let isTestPassed: boolean = true;
Here browserName, retryCount, and isTestPassed are variables, while string, number, and boolean are their data types.
Common types:
- string
- number
- boolean
- array
- object
- tuple
- enum
- any
- unknown
- void
- null
- undefined
- never
examples for these Common data types:
1. string — Text
Used for storing text.
let browserName: string = “Chrome”;
Example:
let url: string = “https://example.com";
await page.goto(url);
2. number — Numbers
Used for integers and decimal numbers.
let retryCount: number = 3;
let price: number = 99.50;
Automation example:
let timeout: number = 5000;
await page.waitForTimeout(timeout);
3. boolean — True/False
Used when the value can be only true or false.
let isLoggedIn: boolean = true;
4. array — Multiple Values
An array stores multiple values of the same type.
let browsers: string[] = [“Chrome”, “Firefox”, “Edge”];
let numbers: number[] = [10, 20, 30];
Automation example:
let users: string[] = [“admin”, “user1”, “user2”];
for (let user of users) {
console.log(user);
}
5. object — Collection of Properties
An object stores related information as key-value pairs.
let loginData: {
username: string;
password: string;
} = {
username: “admin”,
password: “Admin@123”
};
6. tuple — Fixed Order and Number of Values
A tuple allows you to specify the type and order of each element.
let user: [string, number] = [“Manjiri”, 30];
Here:
- First value must be string
- Second value must be number
7. enum — Predefined Set of Values
An enum is useful when you have a fixed set of possible values.
enum Environment {
DEV = “DEV”,
UAT = “UAT”,
PROD = “PROD”
}
let environment: Environment = Environment.UAT;
8. any — Any Type
any means TypeScript can accept almost any value.
“Don’t check the type.”
let data: any = “Hello”;
data = 100;
data = true;
data = [“Chrome”, “Firefox”];
9. unknown — Unknown Type
unknown is also used when you don’t know the type, but it is safer than any.
let data: unknown = “Hello”;
any → TypeScript doesn’t force you to check.
unknown → TypeScript forces you to check before using the value.
10. void — No Return Value
Usually used for a function that doesn’t return anything.
function printMessage(): void {
console.log(“Hello”);
}
11. null — Intentionally Empty Value
null means the value is intentionally set to “nothing.”
let testData: string | null = null;
Later:
testData = “Login Test”;
12. undefined — Value Not Assigned
undefined generally means a value hasn’t been assigned./ value is not currently available/assigned.
let username: string | undefined;
console.log(username);
The value is undefined.
You can later assign:
username = “Manjiri”;
13. never — Never Successfully Completes
never is used when a function never returns normally.
For example, a function that always throws an error:
function throwError(): never {
throw new Error(“Something went wrong”);
}
Q. 4. What is a type?
A type in TypeScript defines what kind of value a variable can hold. We can use built-in types like string, number, and boolean, or create custom types to define the structure of objects and data
E.g.
let username: string = “Manjiri”;
let age: number = 30;
let isActive: boolean = true;
Here:
- string → type of username
- number → type of age
- boolean → type of isActive
You can also create your own type
type User = {
username: string;
age: number;
};
let user: User = {
username: “Manjiri”,
age: 30
};
Here, User is a custom type that defines the structure of the user object.
Q. 5 Difference between type and interface?
Both type and interface can be used to define object structures. Interfaces are mainly used for object-oriented structures and can be extended using extends, while types are more flexible and can also define unions, tuples, and other types. In automation, I can use either depending on the requirement
Example
Interface:
interface User {
username: string;
age: number;
}
Type:
type User = {
username: string;
age: number;
};
Main differences
interface
type
Mainly used to define object/class structure
Can define objects, unions, primitives, tuples, etc.
Can be extended using extends
Can combine types using &
Supports declaration merging
Does not support declaration merging
Commonly used for object structures
More flexible
Q.6) What is async/await?
async/await is used in JavaScript/TypeScript to handle asynchronous operations and wait for them to complete. This is very important in Playwright because most Playwright actions are asynchronous.
async/await is used to handle asynchronous operations. async defines an asynchronous function, and await waits for an asynchronous operation to complete before moving to the next step. In Playwright, we use it with actions like goto, click, fill, and assertions
async function login() {
await page.locator(“#username”).fill(“admin”);
await page.locator(“#password”).fill(“Admin@123”);
await page.locator(“#login”).click();
}
Why do we use it in Playwright?
Without properly waiting for asynchronous operations, the next step could execute before the previous operation is completed.
Asynchronous = an operation that takes time to complete, and the program handles it without treating it as an immediate result.
Q. 7. What is a Promise?
A Promise represents the result of an asynchronous operation. It can be pending, fulfilled, or rejected. In Playwright, methods like goto(), click(), and fill() return Promises, so we use await to wait for them to complete.
Easy way to remember
Promise = result will come later
await = wait for that result
Get Manjiri kalkundrikar’s stories in your inbox
Join Medium for free to get updates from this writer.
Q. 8) What is type inference?
Type inference is a TypeScript feature where the compiler automatically determines the type of a variable based on the value assigned to it, so we don’t always need to explicitly specify the type
Playwright
const browserName = “Chrome”;
const timeout = 5000;
TypeScript automatically infers:
browserName → string
timeout → number
Q.9) What is optional parameter?
An optional parameter is a function parameter that is not mandatory. In TypeScript, we use ? after the parameter name to make it optional
Easy to remember:
name: string → Required
name?: string → Optional
Simple example
function login(username: string, password?: string) {
console.log(username);
}
login(“admin”); // Valid
login(“admin”, “Admin@123”); // Also valid
The username is required, but password is optional.
Q.10) What is union type?
A union type allows a variable or parameter to accept multiple types or predefined values. We use the | (pipe) symbol to define a union type
Simple example
let userId: string | number;
userId = 101; // Valid
userId = “USER101”; // Valid
Here, userId can be either a number or a string.
In Playwright
You might define a reusable type:
type BrowserName = “chromium” | “firefox” | “webkit”;
let browser: BrowserName = “chromium”;
Now only these three values are allowed.
Q.11) What is type assertion?
Type assertion is a way of telling TypeScript what type we believe a value has. It doesn’t convert or change the value; it only provides type information to TypeScript.
For example:
let value = “123”;
let num = value as number;
This does not actually convert “123” into the number 123. For conversion, you would use something like Number(value).
Q.12) How do you import/export classes?
In Playwright POM, I export Page Object classes from their respective files and import them into the test files using import. This allows us to reuse the Page Object classes and keep the automation code organized and maintainable
Easy way to remember
export → make the class available
import → use the class in another file
Page Object classes are usually kept in separate files and then imported into your test files.
1. Export a class
Suppose you have LoginPage.ts:
import { Page } from ‘@playwright/test’;
export class LoginPage {
constructor(private page: Page) {}
async login(username: string, password: string) {
await this.page.locator(‘#username’).fill(username);
await this.page.locator(‘#password’).fill(password);
await this.page.locator(‘#login’).click();
}
}
The keyword export makes the LoginPage class available to other files.
2. Import the class
In your test file:
import { LoginPage } from ‘./LoginPage’;
Then create an object:
const loginPage = new LoginPage(page);
await loginPage.login(‘admin’, ‘Admin@123’);
So the flow is:
LoginPage.ts
export class LoginPage
⬇️
login.spec.ts
import { LoginPage }
⬇️
new LoginPage(page)
Q.13) What is tsconfig.json?
tsconfig.json is the configuration file for a TypeScript project. It defines compiler and type-checking settings such as the JavaScript target, module system, and strict type checking.
In Playwright
A Playwright project can have:
Playwright Project
│
├── tests/
├── pages/
├── playwright.config.ts
├── tsconfig.json
└── package.json
tsconfig.json controls the TypeScript settings, while playwright.config.ts controls Playwright settings such as browsers, timeout, retries, base URL, etc.
Simple example
{
“compilerOptions”: {
“target”: “ES2020”,
“module”: “commonjs”,
“strict”: true
}
}
Q.14) How do you define test data using TypeScript?
In Playwright, I can define test data using TypeScript objects, arrays, interfaces, or types. For structured and reusable data, I prefer defining an interface or type and then creating test data based on it. For data-driven testing, I can store multiple test-data objects in an array.
1. Using an object
For simple test data:
const loginData = {
username: “admin”,
password: “Admin@123”
};
Use it in the test:
await loginPage.login(loginData.username, loginData.password);
2. Using an interface ⭐
For structured and reusable test data:
interface LoginData {
username: string;
password: string;
}
const loginData: LoginData = {
username: “admin”,
password: “Admin@123”
};
Now TypeScript ensures that username and password have the correct types.
3. Using an array for multiple test data
This is useful for data-driven testing:
const loginUsers: LoginData[] = [
{
username: “admin”,
password: “Admin@123”
},
{
username: “user1”,
password: “User@123”
}
];
Then you can loop through the data:
for (const user of loginUsers) {
await loginPage.login(user.username, user.password);
}
Q.15) Generics
Generics allow us to create reusable code that can work with different data types while still maintaining type safety.
Simple example
function getValue<T>(value: T): T {
return value;
}
let name = getValue<string>(“Manjiri”);
let age = getValue<number>(30);
Here:
- T is a generic type parameter
- T can represent string, number, or another type
- The same function can be reused with different types
Q. 16) How do you handle errors using try/catch in TypeScript/Playwright?
try/catch is used to handle errors without immediately stopping the entire program or test flow. We put the code that may cause an error inside try, and handle the error inside catch.
- try → contains the code that may fail.
- catch → executes if an error occurs.
- error → contains information about the error.
Playwright example
async login() {
try {
await this.username.fill(“admin”);
await this.password.fill(“Admin@123”);
await this.loginButton.click();
} catch (error) {
console.log(“Login failed:”, error);
throw error;
}
}
Here, throw error is useful when we want to log the error but still let the Playwright test fail, rather than hiding the failure.
Easy memory:
try → perform action
catch → handle error
throw → pass the error back so the test can fail properly.
Q.17) How do you use interfaces/types in API response or test data?
I use interfaces or types to define the expected structure of test data and API responses. This provides type safety and makes the code easier to understand and maintain. For example, I can define an interface for login data with username and password, and then create test data based on that interface
Q.18) What is the difference between let, const, and var?
let, const, and var are used to declare variables. let allows reassignment and is block-scoped, while const does not allow reassignment and is also block-scoped. var is function-scoped and is generally avoided in modern TypeScript. I mainly use const by default and let when the value needs to change
Q.19) What is the difference between == and ===?
== compares values and can perform type conversion, while === compares both value and data type without type conversion. In TypeScript and modern JavaScript, I generally prefer === because it provides strict and predictable comparison
1. == — Loose equality
It compares the values after type conversion if necessary.
console.log(5 == “5”); // true
Although one is a number and the other is a string, == converts them before comparing.
2. === — Strict equality
It compares both value and data type.
console.log(5 === “5”); // false
Because:
- 5 → number
- “5” → string
The types are different, so the result is false.
Easy memory:
== → value comparison with conversion
=== → value + type comparison







