Playwright + TS · Lesson 5 of 36

0/36 done

Module 5: TypeScript Functions

5. Parameter Types, Default Values & Return Signatures

10 minlesson

Your task

Create a function retryAction with:

  • parameter actionName of type string
  • parameter maxAttempts of type number with default value 3
  • return type string that returns "${actionName} configured with ${maxAttempts} attempts".

Write it in the editor, then press Check answer (Ctrl + Enter).

Typing Functions in TypeScript

typescript
// Explicit parameter types and return type:
function calculateTimeout(retries: number, baseTimeout: number = 5000): number {
  return baseTimeout * (retries + 1);
}

// Optional parameter (?):
function logResult(testName: string, durationMs?: number): void {
  if (durationMs !== undefined) {
    console.log(`${testName} finished in ${durationMs}ms`);
  } else {
    console.log(`${testName} finished`);
  }
}

// Async function return signature: always Promise<T>
async function fetchToken(apiUrl: string): Promise<string> {
  return "auth_token_xyz";
}

Key Takeaways & Walkthrough Summary

Now that you know basic TypeScript types, let's look at functions in TypeScript. We will learn how to define parameter types, return types, optional and default parameters, and strongly typed callbacks. This gives you complete confidence when building reusable automation utility functions. Let's get started!

Part of the Playwright + TS course (Playwright with TypeScript). Practice this concept live in the Playwright Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

Why does an async function always return Promise<T> even if I return a raw string?

JavaScript async functions automatically wrap whatever you return inside a Promise. In TypeScript, the return type must be written as Promise<string>.

Ready? Solve the task in the editor

Use Check answer to mark it complete. Hints are there if you need them.

TypeScript
Skip