QA AND TEST AUTOMATION · PART 2 · PROGRAMMING FOR TESTERS · TYPESCRIPT · 26 OF 112

TypeScript Basics for Playwright Testers

The TypeScript a Java tester needs to read and write Playwright tests: let and const, types and interfaces, arrow functions, template strings, === versus ==, arrays and objects, and above all async and await, because every browser action returns a promise. Ends with a first Playwright test on the ShopRung search, compared line by line with Java.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 67
  63. 68
  64. 69
  65. 70
  66. 71
  67. 72
  68. 73
  69. 74
  70. 75
  71. 76
  72. 77
  73. 78
  74. 79
  75. 80
  76. 81
  77. 82
  78. 83
  79. 84
  80. 85
  81. 86
  82. 87
  83. 88
  84. 89
  85. 90
  86. 91
  87. 92
  88. 93
  89. 94
  90. 95
  91. 96
  92. 97
  93. 98
  94. 99
  95. 100
  96. 101
  97. 102
  98. 103
  99. 104
  100. 105
  101. 106
  102. 107
  103. 108
  104. 109
  105. 110
  106. 111
  107. 112
1 / 13

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • const and let
  • types and interfaces
  • arrows and templates
  • ===
  • array methods
  • await every action

Notes

What it is

JavaScript is the language of the web, and Node.js runs it outside the browser. TypeScript is JavaScript plus types, checked before the code runs, which catches typos and wrong arguments early, the way the Java compiler does. Playwright Test runs dot t s files directly, with no separate build step. To start, install the Node long term support version, then run npm init playwright at latest in an empty folder.

TypeScript in one breath
  • JavaScript: the language of the web, runs in Node.js
  • TypeScript: JavaScript + types checked by the compiler
  • Playwright runs .ts test files directly, no build step
  • install Node.js LTS
  • npm init playwright@latest

Variables

Use const for values that never change, which is most of them, and let for ones that do, like a retry counter. Avoid the old var keyword. Types go after a colon: number, string, boolean. Often you can leave them out and TypeScript infers them, like var in Java. One important difference: number is one type for whole numbers and decimals, and it behaves like a double. So the money rule still applies: compare cents, not dollar decimals.

Variables and types
const url = "http://localhost:8080";
let retries = 0;
retries++;

const qty: number = 4;
const code: string = "SAVE10";
const inStock: boolean = true;

// number: one type for ints
// AND decimals (like double)

Objects

In TypeScript you often create objects directly with curly braces, no class needed. An interface describes the shape of an object, its fields and types. Here a product has a sku, a name, a price in cents and an in stock flag, exactly like ShopRung's API returns. Declare the mug as a product and the compiler checks every field. Interfaces are how you type API responses in tests, so a typo like price cent is caught before the test runs.

Interfaces and objects
interface Product {
  sku: string;
  name: string;
  priceCents: number;
  inStock: boolean;
}
const mug: Product = {
  sku: "MG-201", name: "Green
  Build Mug", priceCents: 1500,
  inStock: true };
mug.priceCents   // 1500

Functions

Functions can be written with the function keyword, or as arrow functions, which you will see everywhere in Playwright. Backticks make template strings, where dollar and curly braces insert a value, like Hi comma user's name. The money function turns cents into text the way ShopRung does: forty nine ninety nine for four thousand nine hundred ninety nine cents. Arrow functions are like Java lambdas, and they are what you pass to array methods.

Functions
function money(c: number): string {
  return `$${Math.floor(c / 100)}.` +
    `${String(c % 100)
      .padStart(2, "0")}`;
}
const isCheap = (p: Product) =>
  p.priceCents < 1000;

money(4999)    // "$49.99"
`Hi, ${user.name}` // template

Equality

One JavaScript trap. Double equals converts types before comparing, so zero equals an empty string and the text one equals the number one. Triple equals compares without conversion, which is what you almost always want. Always use triple equals and its opposite, not equals equals. JavaScript also has two kinds of nothing: undefined, a value that was never set, and null, a value set to nothing on purpose.

=== vs ==
0 == ""        // true  (!)
"1" == 1       // true  (!)
null == undefined // true

0 === ""       // false
"1" === 1      // false

always === and !==
undefined: never set
null: set to "nothing"

Arrays

Arrays have methods that work like Java streams, without the stream call. Map transforms each item, filter keeps some, find returns the first match, every and some check conditions, and includes checks membership. One trap: sort with no argument sorts numbers as text, so always pass a compare function, a minus b, and copy the array first with three dots if you need to keep the original order.

Arrays
const prices = [1500, 499, 12999];
prices.length            // 3
prices.map(money)
// ["$15.00","$4.99","$129.99"]
prices.filter(c => c < 1000)
// [499]
prices.every(c => c > 0) // true
prices.includes(499)     // true
[...prices].sort((a, b) => a - b)
// [499, 1500, 12999]

async and await

Now the most important part. Every browser action, a click, a fill, a page load, talks to a browser running in another process, so it takes time. Each one returns a promise, a value that will arrive later. Write await before it, and your test waits for the action to finish before the next line. Forget the await, and the test races ahead before the click happens, which causes flaky tests. A function that uses await must be marked async.

await every action
// a click talks to a browser in
// another process: it takes time
await page.click("text=Search");

// forgetting await:
page.click("text=Search");
// test moves on before the
// click happens → flaky test

functions using await are
  marked async

A first test

Here is a first Playwright test, for ShopRung's rule that search is not case sensitive. Import test and expect. Name the test, and receive a page as a fixture. Go to the shop. Find the search box by its role and its label, search products, and type MUG in capitals. Press enter. Then expect the result count to have the text two products. The expect line waits and retries until it is true or times out, which you will learn properly in Part five.

search.spec.ts
import { test, expect } from
  "@playwright/test";
test("search is not case-
    sensitive", async ({ page }) => {
  await page.goto("/"); // baseURL
  await page.getByRole("searchbox", {
    name: "Search products" }).fill("MUG");
  await page.keyboard.press("Enter");
  await expect(page
    .getByTestId("result-count"))
    .toHaveText("2 products");

Java vs TS

A quick translation table. Final becomes const. A type before the name becomes a type after a colon. Records and data classes often become interfaces. Lambdas use a fat arrow, equals and greater than instead of a thin one. Stream map becomes plain map. Equals becomes triple equals. At test becomes a test function call, and assert equals becomes expect to be. The ideas you learned in Java carry over almost one to one.

Java → TypeScript
final int q = 4;  → const q = 4;
String s         → s: string
record / class   → interface
p -> p.stock()   → p => p.stock
.stream().map   → .map
equals()         → ===
void m() {}      → async () => {}
@Test            → test("...", ..)
assertEquals     → expect(..).toBe

Common mistakes

TypeScript mistakes in Playwright tests. A missing await, the number one cause of flaky tests. Double equals instead of triple. Sorting numbers without a compare function. Typing everything as any, which switches off the checks you came for. Money as decimals. Await inside for each, which does not wait; use a for of loop instead. And hard coded addresses; Playwright's config has a base URL setting.

Avoid these
  • missing await (flaky!)
  • == instead of ===
  • sort() on numbers with no compare function
  • any everywhere (no checks)
  • money as decimals
  • await inside forEach (use for...of)
  • hard-coded URLs: use baseURL in the config

Say it like this

A favourite question: why do Playwright tests need await? Say: every Playwright action talks to the browser asynchronously and returns a promise. Await makes the test wait for it, so steps run in order. A missing await lets the test move on before the action finishes, which causes flaky failures. Add that a lint rule for floating promises catches missing awaits automatically. That answer shows you understand the tool, not just the syntax.

In the interview
  • "Every Playwright action talks
  • to the browser asynchronously
  • and returns a promise. await
  • makes the test wait for it, so steps run in order. A missing await lets the test
  • move on early, which causes
  • flaky failures. Linters can
  • flag floating promises."

Interview questions

Q1What is the difference between TypeScript and JavaScript?

TypeScript adds static types to JavaScript; the compiler checks them before running and then produces plain JavaScript. Playwright Test runs .ts files directly.

Q2What is the difference between == and === in JavaScript?

== converts types before comparing (0 == "" is true); === compares value and type without conversion. Use === and !==.

Q3What do async and await do?

async marks a function that returns a promise; await pauses inside it until a promise settles, so asynchronous steps run in order.

Q4What happens if you forget await before a Playwright action?

The test continues before the action completes, causing race conditions and flaky failures; the promise may also reject unnoticed.

Q5What is the difference between let, const and var?

const cannot be reassigned, let can; both are block-scoped. var is function-scoped and hoisted, a source of bugs, so it is avoided.

Q6What is an interface in TypeScript?

A description of an object's shape (field names and types), used to type data such as API responses; it exists only at compile time.

Q7Why can await inside forEach be a problem?

forEach does not wait for async callbacks, so iterations run without waiting; use a for...of loop with await, or Promise.all for intended parallelism.

Q8What is the difference between null and undefined?

undefined means a value was never assigned; null is an explicit "no value". Both are falsy; check with === or optional chaining (?.).