TypeScript

18 topics across 4 levels
TypeScript/Basic · Topic 2

Functions, Optional & Default Parameters

Write typed helper functions for test setup without runtime guesswork.

Annotate parameters and return types on any function that isn't a trivial one-off — TypeScript infers return types fine, but writing them explicitly catches you when a code path silently returns undefined.

Optional parameters (name?: string) must come after required ones and are typed T | undefined. Default parameters (retries = 3) are inferred as their default's type and are always optional to the caller.

Real-world use case

A login(page, username, password?) helper used across a suite, where omitting the password should fall back to a shared test account instead of crashing.

Example code

src/helpers/login.ts
import { Page } from "@playwright/test";

async function login(
  page: Page,
  username: string,
  password: string = "Str0ng!Pass",
  retries: number = 1
): Promise<void> {
  for (let attempt = 0; attempt < retries; attempt++) {
    await page.goto("/login");
    await page.locator("#user-name").fill(username);
    await page.locator("#password").fill(password);
    await page.locator("#login-button").click();
  }
}

Reference links

Typed retry helper

Write a function withRetry<T>(fn: () => Promise<T>, retries = 3): Promise<T> that calls fn, retrying up to retries times on failure, and rethrows the last error.

Loading editor…
Execution isn't wired up yet — this editor is for writing/reviewing, not running.