TypeScript Variables and Data Types
TypeScript adds static types to JavaScript, making test automation code easier to read, validate and maintain.
What are variables and data types?
A variable stores a value. A type describes the kind of value it can contain.
const browserName: string = "Playwright";
const retryCount: number = 2;
const isHeadless: boolean = true;
console.log(browserName);
console.log(retryCount);
console.log(isHeadless);
Why is it important?
Types detect mistakes before runtime and help editors provide accurate completion and refactoring support.
let, const and var
Use const for values that do not change and let for values that do.
const baseUrl: string = "https://example.test";
let attemptCount: number = 0;
attemptCount += 1;
Avoid var in modern TypeScript test code because block scope and type-safe readability are preferable.
Type inference
TypeScript does not always require an annotation.
const timeout = 30_000; // inferred as number
const message = "Test passed"; // inferred as string
Arrays and objects
const browsers: string[] = ["chromium", "firefox"];
interface TestUser {
email: string;
role: "admin" | "customer";
}
const user: TestUser = {
email: "tester@example.com",
role: "customer",
};
Common mistakes
- Using
anywhere a useful type is available. - Using
asto silence an incorrect model. - Modeling optional values without the
?orundefinedunion. - Treating runtime validation as unnecessary just because an API response is typed.
Real-world automation example
interface LoginCredentials {
email: string;
password: string;
}
async function login(page: any, credentials: LoginCredentials): Promise<void> {
await page.getByLabel("Email").fill(credentials.email);
await page.getByLabel("Password").fill(credentials.password);
await page.getByRole("button", {name: "Sign in"}).click();
}
Summary
- TypeScript improves code clarity and catches type mistakes.
- Use
const,let, inferred types and named interfaces deliberately. - Typed test data makes automation configuration easier to maintain.