The Testing Academy · Class Notes Wednesday, 25 November (IST)
Live class · study guide

TypeScript generics, access modifiers and abstract classes

Generics: one function or one class for any type, with a placeholder T; public, private and protected in an API client and a base page; private readonly; abstract classes against interfaces; then a tour of the Playwright page, for the classes to come. Files 233 to 239.

By Pramod Dutta, The Testing Academy. Study notes from the Playwright 4x class of Wednesday, 25 November, built from the session recording, the batch repository, which received files 233 to 239, README sections for chapters 33 to 35 and three cheat-sheet images in the last minutes of the class (commit "feat: add generics, modifiers, abstract classes", which also renamed 231.API.ts to 232.API.ts), and the Eraser notes deck, whose section for this class holds notes on generics and on private, public and protected, a run command and the closing tasks. Every class file was compiled with TypeScript 6.0.2, the version the batch's class used on 18 and 20 November, with the repo's tsconfig.json, then run with Node 22, and run again with Node alone and with tsx 4.23.15. The outputs are what each run prints, errors included, with tsc's errors in the layout it prints in a terminal, colours aside; local paths are made relative to the repo. In file 236, the key passed in on line 31 is shown as a placeholder. The lines added, switched on or taken out, the README's added lines, the copy of getFirstResult written with any, the two modules that call navigate() and the interface with four methods were run for this page, and the types in the tables were read from TypeScript's own compiler. The tour uses the Playwright page's own names. None of the class's code makes a network request, and nothing on this page signs in anywhere.

Hides every output until you tap Reveal, so you can predict it first.
01

What this class covered

  • Generics: a placeholder for the type
  • A generic function: getFirstResult
  • A generic class: a test data store
  • A generic API response wrapper
  • public, private and protected: an API client
  • A base page with protected members
  • readonly: set only one time
  • Abstract classes: incomplete functions
  • Abstract class versus interface
  • An interface is just rules
  • Running a TypeScript file
  • The Playwright page: a tour
  • Questions at the end: Markdown files, agents and skills
  • Tasks: the exercises up to 239 on GitHub, and a Playwright folder in a new repo
  • A generic writes the type as a placeholder, T, and the call fills it in: one getFirstResult<T>() takes numbers, strings or booleans. any takes them all too, but nothing is checked.
  • T is fixed at each call and for each object: getFirstResult<number>([1, "a"]) is TS2322, and adding a string to a TestDataStorage<number> is TS2345. The letter T is only a convention.
  • ! after a value only tells the compiler that the value is there. It checks nothing at run time: an empty array still gives undefined.
  • public is open everywhere; protected is for the class and its child classes (TS2445 from outside), and private for that class only (TS2341). They are compile-time rules: a private field is still readable in the running JavaScript, and a # field is not.
  • protected follows classes, not folders: a child class in another folder may use it, and a class in the same folder that is not a child may not.
  • A private readonly field is set in the constructor, and after that even its own class cannot change it (TS2540), very similar to final in Java.
  • An abstract class can hold variables, a constructor and complete functions next to incomplete ones, which a child class must write (TS2515); it cannot be created with new (TS2511). It is a real class in the compiled JavaScript, while an interface leaves nothing. To force rules on a class, interfaces with normal classes are the best combination, the instructor said.
02

Generics: a placeholder for the type

This class went on from the 20 November notes, on abstraction, interfaces and enums.

ONE TYPE ONLY, ANY TYPE UNCHECKED, OR A PLACEHOLDER A HARD-CODED TYPE, LINE 1 getString(name: string): string a string in, a string out and nothing else getString("pramod") no error getString(123) TS2345 ANY, WITH NO SAFETY getFirstAny(result: any[]): any any type in, any type out, and nothing is checked let first: string = getFirstAny([200, 400, 500]); no error first, typed as a string, holds the number 200 A PLACEHOLDER, LINE 8 getFirstResult<T>(result:T[]):T T is filled in at the call, and TypeScript knows the exact type that comes back T = number 200 T = string Login T = boolean true let first: string = getFirstResult<number>([200, 400, 500]); TS2322
File 233 with real runs: a hard-coded type takes one type only, any takes every type and checks none, and T takes every type and is still checked.

Three more topics were to be covered, the instructor said, and the first is generics: a simple concept, very similar to Java's, also available in Python, and very common in all the programming languages. Whenever we create a function, the data type has to be hard-coded: the name is a string, and it returns a string. In TypeScript we have to mention clearly which data type to go with. File 233_Generic_Method.ts starts with a function like that:

233_Generic_Method.tsTypeScript
function getString(name: string): string {
    return "Amit";
}

getString("pramod");
// getString(123);

Is this function generic in nature, the instructor asked the class? No: it clearly says that this is a string, and the return is a string too. You can call it with a name, and there is no problem. Can you run it with 123? No, because the two data types do not match. Line 6, switched on:

TypeScript
getString(123);
Output
33_OOPs_Generic/233_Generic_Method.ts:6:11 - error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'.

6 getString(123);
            ~~~


Found 1 error in 33_OOPs_Generic/233_Generic_Method.ts:6

What if this were possible, the instructor asked: how cool is that? Generics basically let you write code that works with any type of data, the instructor said. You do not mention the data type; you write a T, generally used as a template, or a placeholder for the actual type whenever you call the function. The deck's note says the same, and adds "while staying type-safe": <T> is a placeholder, replaced with the actual type when you call the function.

Why do we need generics, some people will say, when we can use any too? any can be any data type, but it has no safety, the instructor said; it is avoided sometimes, and generics are mostly used for that. The deck's note: without generics, you'd use any, with no safety, or duplicate the code for each type. Here is the missing safety, on the class's own array: getFirstAny is a copy of the next section's function, written with any.

Line What tsc says
let first: string = getFirstAny([200, 400, 500]); no error: first, typed as a string, holds the number 200
let first: string = getFirstResult<number>([200, 400, 500]); TS2322: Type 'number' is not assignable to type 'string'

A generic can be a function, a class or an interface, and it can have multiple parameters, the instructor said; in the real world, generics can also be used when you parse a JSON. The deck writes each one out:

What The deck's line
A generic function function getFirst<T>(arr: T[]): T
A generic class class DataStore<T> { private items: T[] = [] }
A generic interface interface APIResponse<T> { status: number; data: T }
Several type parameters function pair<K, V>(key: K, value: V)

The deck's note adds a real use: parseResponse<UserData>(res) against parseResponse<OrderData>(res), the same function with different types.

03

A generic function: getFirstResult

A cheat sheet titled Generics: One Function, Any Type. A blue card, The generic function, holds getFirstResult<T>(result: T[]): T. Three green arrows lead to three white cards: getFirstResult<number>([200, 400]) gives 200, getFirstResult<string>(["Login"]) gives "Login" and getFirstResult<boolean>([true]) gives true. A red card holds getFirstResult<number>([1, "a"]) and TS2322. An orange banner at the bottom reads: T is a placeholder, filled in when you call it.
From the batch repo's README: the sheet's arrays are shorter than file 233's, and give the same first elements; the red box's error is shown below as tsc prints it.

So the instructor wrote a function that gets the first result. When you declare it, you say that it is a type of T: it takes a T array and returns a T, here the first element of the array. The rest of file 233:

233_Generic_Method.tsTypeScript
function getFirstResult<T>(result:T[]):T{
    return result[0]!; // ! = non null assertion operator
}

let firstNumber = getFirstResult<number>([200, 400, 500]);
let firstString= getFirstResult<string>(["Login", "Signup", "Cart"]);
let firstBoolean = getFirstResult<boolean>([true, false, true]);

console.log("First code:", firstNumber);
console.log("First test:", firstString);
console.log("First test:", firstBoolean);
Output
First code: 200
First test: Login
First test: true

It can take the numbers array and give you the first element, and the same function can take strings, or true and false, which is a boolean, the instructor said. Run it, and you get 200, Login and true: the first elements are coming. In Playwright, you will see this a lot of times. TypeScript knows what comes back from each call, as its own compiler lists it:

Call T What comes back Prints
getFirstResult<number>([200, 400, 500]) number firstNumber: number 200
getFirstResult<string>(["Login", "Signup", "Cart"]) string firstString: string Login
getFirstResult<boolean>([true, false, true]) boolean firstBoolean: boolean true

The README puts it this way: one helper works for status codes, test names and flags, and TypeScript still knows the exact type that comes back. Once the call says number, a string in the array is refused, as on the cheat sheet. With a line 20 added:

TypeScript
getFirstResult<number>([1, "a"]);
Output
33_OOPs_Generic/233_Generic_Method.ts:20:28 - error TS2322: Type 'string' is not assignable to type 'number'.

20 getFirstResult<number>([1, "a"]);
                              ~~~


Found 1 error in 33_OOPs_Generic/233_Generic_Method.ts:20

The ! on line 9 is the non-null assertion operator, as the file's comment calls it. It means that in the end this element should not be null, the instructor said: it should be something. The README says what that is worth: the ! promises TypeScript that the value is there, which is needed because tsconfig.json sets noUncheckedIndexedAccess. Without it, line 9 is refused:

TypeScript
return result[0];
Output
33_OOPs_Generic/233_Generic_Method.ts:9:5 - error TS2322: Type 'T | undefined' is not assignable to type 'T'.
  'T' could be instantiated with an arbitrary type which could be unrelated to 'T | undefined'.

9     return result[0];
      ~~~~~~


Found 1 error in 33_OOPs_Generic/233_Generic_Method.ts:9

What will the result be if the first element of the array is 0? The question came up in class. If it is a 0, or if there is no element at all, it does not give you an error, the instructor said. The file's first call, and the two from the question, added at the end of the file:

Call What tsc says Prints
getFirstResult<number>([200, 400, 500]) no error 200
getFirstResult<number>([0, 400, 500]) no error 0
getFirstResult<number>([]) no error undefined

There is no error in any of them, and a 0 comes back as 0. The README's gotcha is the last row: the ! checks nothing at run time, so an empty array still gives undefined.

04

A generic class: a test data store

Can a class be generic too, the instructor asked? Absolutely. The <T> after the class's name is a way of telling that it is a template type, or generic in nature. File 234_Generic_Class.ts:

234_Generic_Class.tsTypeScript
class TestDataStorage<T> {
    private items: T[] = [];
    add(item: T): void {
        this.items.push(item);
    }
    getFirst(): T {
        return this.items[0]!;
    }
    getAll(): T[] {
        return this.items;
    }

    count(): number {
        return this.items.length;
    }
}

let statuscodeStore = new TestDataStorage<number>();
let testNameStore = new TestDataStorage<string>();

statuscodeStore.add(200);
statuscodeStore.add(404);
statuscodeStore.add(500);

testNameStore.add("Login Test");
testNameStore.add("Checkout Test");


console.log("Codes:", statuscodeStore.getAll());
console.log("First code:", statuscodeStore.getFirst());
console.log("Tests:", testNameStore.getAll());
console.log("Test count:", testNameStore.count());
Output
Codes: [ 200, 404, 500 ]
First code: 200
Tests: [ 'Login Test', 'Checkout Test' ]
Test count: 2

Is any data type mentioned here, the instructor asked? Only T: it takes a T array, and you can add to it, get the first element, get all the elements and count them, all of it based on T. You can call it with number and with string, both are supported, and all the methods are absolutely going to work.

Where are these used? Widely in API testing, the instructor said. You make an API request and get a response, and you are not sure what kind of response you will get: a number, a string, a boolean? In that case, we use templates.

T is just an example, the instructor said, and it can be anything: O, P, R, X, Q or a name. But T is generally used, for template, so that everyone recognizes it. With every T of the class renamed to X, file 234 compiles and prints the same four lines.

The README adds that T is fixed for each object: a store of numbers takes numbers only. With a line 33 added:

TypeScript
statuscodeStore.add("500");
Output
33_OOPs_Generic/234_Generic_Class.ts:33:21 - error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.

33 statuscodeStore.add("500");
                       ~~~~~


Found 1 error in 33_OOPs_Generic/234_Generic_Class.ts:33

And getFirst() on an empty store returns undefined, although its type says T, as the README notes: its ! is the one from file 233.

TypeScript
let emptyStore = new TestDataStorage<number>();
console.log(emptyStore.getFirst());
Output
undefined
05

A generic API response wrapper

Then a real example, generics with the API, so that you can relate to it, the instructor said. The function wraps a response, and you are not sure about the data type: what you will send can be a number, a string, a boolean or something, and what you will get is not sure either. That is why T is used. File 235_REAL_Generic_API.ts:

235_REAL_Generic_API.tsTypeScript
function wrapResponse<T>(statusCode: number, data: T): { statusCode: number; data: T } {
    return { statusCode: statusCode, data: data };
}

let userResp = wrapResponse<string>(200, "admin");
console.log(userResp);

let flagResp = wrapResponse<boolean>(200, true);
console.log(flagResp);
Output
{ statusCode: 200, data: 'admin' }
{ statusCode: 200, data: true }

You can call this function with a string, admin, and also with a boolean, the instructor said: the same function can be used for both, and that is the beauty of generics. The status code stays a number, and only data follows T, as TypeScript's compiler lists it:

Call What comes back
wrapResponse<string>(200, "admin") { statusCode: number; data: string; }
wrapResponse<boolean>(200, true) { statusCode: number; data: boolean; }

Can let and var be used for generics, a learner asked? Generics are always used with functions, classes and interfaces, the instructor said; with normal variables, you will not use templates.

06

public, private and protected: an API client

A cheat sheet titled public, private, protected: a table of who may use each modifier. Public: same class, child class and outside, all ticked. Protected: same class and child class ticked, outside crossed. Private: same class ticked, child class and outside crossed. Below it, client.apiKey gives TS2341 and client.timeout gives TS2445. An orange banner at the bottom reads: Checked by TypeScript, not at runtime.
From the batch repo's README: its two errors are file 236's, shown below as tsc prints them.

The class had already seen private for JavaScript, with the hash (the 13 November notes). In TypeScript things change a little, the instructor said, because it has proper keywords: public, private and protected. With keywords, this looks much better than with the hash. The deck's note: JavaScript only has public, the default, and #private, and TypeScript adds protected, which JavaScript completely lacks. File 236_PPP.ts, with the key passed in on line 31 shown as a placeholder:

236_PPP.tsTypeScript
class APIClient{
        public baseURL: string;
        private apiKey: string;
        protected timeout: number;

        constructor(baseURL: string, apiKey: string, timeout: number) {
        this.baseURL = baseURL;
        this.apiKey = apiKey;
        this.timeout = timeout;
    }

    private getAuthHeader(): string {
        return "Bearer " + this.apiKey;
    }
    public sendRequest(path: string): void {
        console.log("GET " + this.baseURL + path);
        console.log("Auth: " + this.getAuthHeader());
        console.log("Timeout: " + this.timeout + "ms");
    }
}

class UserAPIClient extends APIClient {

    getUsers(): void {
        console.log("Fetching users (timeout: " + this.timeout + "ms)");
        console.log("URL: " + this.baseURL + "/users");
    }

}

let client = new APIClient("https://api.staging.com", "<api-key>", 5000);
console.log("Base URL:", client.baseURL);
client.sendRequest("/health");
Output
Base URL: https://api.staging.com
GET https://api.staging.com/health
Auth: Bearer <api-key>
Timeout: 5000ms

APIClient has a public base URL, a private key and a protected timeout; a constructor that assigns them; a private function, getAuthHeader(); and sendRequest(), which is public. While the fields were being typed, the message came up that the base URL has no initializer: "That is fine," the instructor said. It is tsc's TS2564, and the constructor's lines 7 to 9 settle it. client.baseURL is available on line 32 because it is public in nature.

UserAPIClient extends APIClient, an example of single inheritance, and its getUsers() uses the parent's timeout and baseURL. Can we use the private variable there, the instructor asked the class? No. Public, yes. Protected? Absolutely, it is allowed. File 236 never makes a UserAPIClient, so two lines added at the end do:

TypeScript
let users = new UserAPIClient("https://api.staging.com", "<api-key>", 5000);
users.getUsers();
Output
Fetching users (timeout: 5000ms)
URL: https://api.staging.com/users

The child's this.apiKey, added after line 26, is refused:

TypeScript
console.log("Key: " + this.apiKey);
Output
34_private_public_protected/236_PPP.ts:27:36 - error TS2341: Property 'apiKey' is private and only accessible within class 'APIClient'.

27         console.log("Key: " + this.apiKey);
                                      ~~~~~~


Found 1 error in 34_private_public_protected/236_PPP.ts:27

From outside, through client, both the private and the protected field are refused, as on the cheat sheet. With two lines added at the end:

TypeScript
console.log(client.apiKey);
console.log(client.timeout);
Output
34_private_public_protected/236_PPP.ts:34:20 - error TS2341: Property 'apiKey' is private and only accessible within class 'APIClient'.

34 console.log(client.apiKey);
                      ~~~~~~

34_private_public_protected/236_PPP.ts:35:20 - error TS2445: Property 'timeout' is protected and only accessible within class 'APIClient' and its subclasses.

35 console.log(client.timeout);
                      ~~~~~~~


Found 2 errors in the same file, starting at: 34_private_public_protected/236_PPP.ts:34

Later in the class, the three were put in words: public means accessible everywhere, and private means accessible only in the class. For protected, the deck's note says: accessible inside the class and in child classes, but not from outside. File 236's three fields, with the line that uses each one in APIClient, in UserAPIClient and through client, or tsc's error:

Field Inside the class In its child class From outside
public baseURL yes, line 16 yes, line 26 yes, line 32
protected timeout yes, line 18 yes, line 25 no, TS2445
private apiKey yes, line 13 no, TS2341 no, TS2341

The README's gotcha, which the cheat sheet and the deck have too: TypeScript's private is checked only at compile time, so apiKey is still readable in the running JavaScript, while a #apiKey field stays private at run time as well. The added line console.log(client.apiKey);, with each kind of field, two ways:

Run with With the private field With a hash field in its place
tsc -p ., the repo's tsconfig.json refused, TS2341 refused, TS2339
node 34_private_public_protected/236_PPP.ts, which strips the types and checks nothing prints <api-key> prints undefined
07

A base page with protected members

PROTECTED FOLLOWS CLASSES, NOT FOLDERS FILE 237, LINES 1 TO 10 class BasePage protected baseURL protected navigate(path) the class and child classes A CHILD, IN THE SAME FILE class LoginPage extends BasePage this.navigate("/login") allowed A CHILD, IN ANOTHER FOLDER class CartPage extends BasePage this.navigate("/cart") allowed NOT A CHILD, IN THE SAME FOLDER class NotAPage base.navigate("/cart") TS2445 THE TEST, FROM OUTSIDE let page = new LoginPage(); page.navigate("/login") TS2445
Real runs: a child class may call the protected navigate() from any folder; a class that is not a child, and the test, may not, even in the same folder or the same file.

But to be honest, the instructor said, we have to understand only one concept: in Playwright you will see something called the page object model, and it is created by using these properly. Take a base page, with a protected base URL, a constructor and a protected navigation method. You can extend it and call its constructor; you can call your own login function, and you get all of them, the navigate function and everything. In the file, that child class is LoginPage. File 237_PageObejctMode.ts:

237_PageObejctMode.tsTypeScript
class BasePage{
    protected baseURL: string;

    constructor(url: string) {
        this.baseURL = url;
    }
    protected navigate(path: string): void {
        console.log("Navigating to: " + this.baseURL + path);
    }
}

class LoginPage extends BasePage {
    constructor() {
        super("https://app.staging.com");
    }

    login(user: string): void {
        this.navigate("/login");
        console.log("Typing " + user + " into #username");
        console.log("Clicking #login-btn");
    }
}

let page = new LoginPage();
page.login("admin");
Output
Navigating to: https://app.staging.com/login
Typing admin into #username
Clicking #login-btn

The deck's note: protected is perfect for the page object model, because BasePage can have protected methods that child pages use, but test files cannot access directly. A test that calls navigate() itself, as a line 26, is refused:

TypeScript
page.navigate("/login");
Output
34_private_public_protected/237_PageObejctMode.ts:26:6 - error TS2445: Property 'navigate' is protected and only accessible within class 'BasePage' and its subclasses.

26 page.navigate("/login");
        ~~~~~~~~


Found 1 error in 34_private_public_protected/237_PageObejctMode.ts:26

protected follows classes, not folders. In class, protected was also explained as the same package or the same folder: if you are in the same folder you can extend the base page, and another folder's class should not use it. That is close to Java's rule. TypeScript has no packages and does not look at folders: the rule is the deck's, the class and its child classes, wherever their files are.

Two small modules that import BasePage, lines 1 to 10 of file 237, show it. They are .mts files, which the repo's tsconfig.json lets import one another. A child class in another folder may call the protected method:

TypeScript
import { BasePage } from "../34_private_public_protected/BasePage.mjs";

class CartPage extends BasePage {
    open(): void {
        this.navigate("/cart");
    }
}

new CartPage("https://app.staging.com").open();
Output
Navigating to: https://app.staging.com/cart

A class in BasePage's own folder that does not extend it may not:

TypeScript
import { BasePage } from "./BasePage.mjs";

class NotAPage {
    open(base: BasePage): void {
        base.navigate("/cart");
    }
}
Output
34_private_public_protected/NotAPage.mts:5:14 - error TS2445: Property 'navigate' is protected and only accessible within class 'BasePage' and its subclasses.

5         base.navigate("/cart");
               ~~~~~~~~


Found 1 error in 34_private_public_protected/NotAPage.mts:5

Public, protected and private are very similar to Java, the instructor said.

08

readonly: set only one time

What exactly does readonly do, the instructor asked? It makes sure that these values are stored only one time: one time setting is allowed. The 20 November class had it in an interface; here it is in a class, with private in front. If you come from a Java background, the instructor said, it is very similar to a final: you can assign it one time, and when you try to change it again, it will just say that it is read only. File 238_Readonly.ts:

238_Readonly.tsTypeScript
class PlaywrightConfig {
    private readonly baseURL: string;
    private readonly timeout: number;
    private readonly retries: number;

    constructor(url: string, timeout: number, retries: number) {
        this.baseURL = url;
        this.timeout = timeout;
        this.retries = retries;
    }
    showConfig(): void {
        console.log("URL: " + this.baseURL);
        console.log("Timeout: " + this.timeout + "ms");
        console.log("Retries: " + this.retries);
    }
}

let config = new PlaywrightConfig("https://staging.app.com", 30000, 2);
config.showConfig();

// config.baseURL = "https://other.com";
Output
URL: https://staging.app.com
Timeout: 30000ms
Retries: 2

Line 21, switched on, breaks both rules at once:

TypeScript
config.baseURL = "https://other.com";
Output
34_private_public_protected/238_Readonly.ts:21:8 - error TS2341: Property 'baseURL' is private and only accessible within class 'PlaywrightConfig'.

21 config.baseURL = "https://other.com";
          ~~~~~~~

34_private_public_protected/238_Readonly.ts:21:8 - error TS2540: Cannot assign to 'baseURL' because it is a read-only property.

21 config.baseURL = "https://other.com";
          ~~~~~~~


Found 2 errors in the same file, starting at: 34_private_public_protected/238_Readonly.ts:21

In the README's words, only the class can see the field, and even the class can't change it after the constructor. A change inside showConfig(), after line 14:

TypeScript
this.timeout = 5000;
Output
34_private_public_protected/238_Readonly.ts:15:14 - error TS2540: Cannot assign to 'timeout' because it is a read-only property.

15         this.timeout = 5000;
                ~~~~~~~


Found 1 error in 34_private_public_protected/238_Readonly.ts:15
09

Abstract classes: incomplete functions

A cheat sheet titled Abstract Class: A Half-Built Parent. A blue card, abstract class BaseTest, lists under must be written by the child: abstract setup(): void, abstract execute(): void and abstract teardown(): void; and under ready to use: loan1(): void. A green card below it, class UITest extends BaseTest, holds new UITest("Login") and an arrow up to BaseTest. A red card, not allowed, holds new BaseTest("Login") and TS2511. An orange banner at the bottom reads: Miss one abstract method: TS2515.
From the batch repo's README: the sheet draws file 239 without its fourth abstract method, loan(); both errors are shown below as tsc prints them.

One topic of abstraction was remaining, the abstract class. It is something that we are going to use very less, to be honest, the instructor said, but still here is how to use it. Can an abstract class have an instance variable? Of course, yes. A constructor? Absolutely yes. What makes it abstract is the incomplete functions, here setup(), execute(), teardown() and loan(). Can it have a complete function too? Yes, it can have both: loan1() is complete. It is the very same concept as in Java, the instructor said. File 239_AC.ts:

239_AC.tsTypeScript
abstract class BaseTest{
    protected testName:string;
    constructor(testName: string) {
        this.testName = testName;
    }

    abstract setup():void
    abstract execute():void
    abstract teardown(): void
    abstract loan():void

    loan1(): void{
        console.log("Loan Given already!")
    }
}
class UITest extends BaseTest {
    setup(): void {
        console.log("  Setup: launch browser");
    }
    execute(): void {
        console.log("  Execute: click buttons, fill forms");
    }
    teardown(): void {
        console.log("  Teardown: close browser");
    }
    loan(): void {
        console.log("  GIVE LOAN");
    }
}

It compiles with no errors and prints nothing, because it only defines the two classes, as the README notes. The README's copy adds an object and three calls:

TypeScript
const test = new UITest("Login");
test.setup();      //   Setup: launch browser
test.execute();    //   Execute: click buttons, fill forms
test.loan1();      // Loan Given already!
Output
  Setup: launch browser
  Execute: click buttons, fill forms
Loan Given already!

If a class extends the base test, it has to give the full definition, the instructor said: extending an abstract class forces you to implement all the abstract methods, all of them, and if you do not, you get a compilation error. With loan(), lines 26 to 28, taken out:

TypeScript
class UITest extends BaseTest {
    setup(): void {
        console.log("  Setup: launch browser");
    }
    execute(): void {
        console.log("  Execute: click buttons, fill forms");
    }
    teardown(): void {
        console.log("  Teardown: close browser");
    }
}
Output
35_TS_Abstract_Class/239_AC.ts:16:7 - error TS2515: Non-abstract class 'UITest' does not implement inherited abstract member loan from class 'BaseTest'.

16 class UITest extends BaseTest {
         ~~~~~~


Found 1 error in 35_TS_Abstract_Class/239_AC.ts:16

The abstract class itself cannot be created, as the README and the cheat sheet say. With a line 30 added:

TypeScript
new BaseTest("Login");
Output
35_TS_Abstract_Class/239_AC.ts:30:1 - error TS2511: Cannot create an instance of an abstract class.

30 new BaseTest("Login");
   ~~~~~~~~~~~~~~~~~~~~~


Found 1 error in 35_TS_Abstract_Class/239_AC.ts:30

At least one abstract method? An abstract class should have at least one abstract method, the instructor said, agreeing with a learner. TypeScript does not insist on it: an abstract class with only complete functions compiles, its child class runs, and new on it is still TS2511.

10

Abstract class versus interface

WHAT TSC WRITES FOR EACH ONE AN INTERFACE: A PURE SHAPE interface TestSteps setup(): void execute(): void teardown(): void loan(): void no body, no constructor used with implements AN ABSTRACT CLASS, FILE 239: A PARTIAL BASE abstract class BaseTest protected testName constructor(testName) abstract setup(), execute() abstract teardown(), loan() loan1(), a complete function used with extends tsc tsc IN THE COMPILED JAVASCRIPT zero the interface is erased: it was only rules for TypeScript IN THE COMPILED JAVASCRIPT class BaseTest testName; constructor(testName) { ... } loan1() { ... } a real class, with no abstract methods
Real tsc output: nothing is left of the interface, while the abstract class stays a real class, without its abstract methods.

This is sometimes asked in interviews, the instructor said, and it is a favourite question of interviewers: abstract class versus interface. The differences, as the instructor went through them:

Abstract class Interface
What it is a partial base, with a shared contract a pure shape, with no implementations
A body, the implementation allowed not allowed
Constructor allowed not allowed
Members public or protected, and in TypeScript private too all public
Abstract members such as setup() and execute() all must be abstract
A class uses it with extends implements
In the compiled JavaScript it exists zero

An interface does not have any JavaScript code in the end, the instructor said, and that was one of the interview questions which was asked. The four incomplete functions of file 239, written as an interface:

TypeScript
interface TestSteps {
    setup(): void;
    execute(): void;
    teardown(): void;
    loan(): void;
}

tsc writes nothing for it. For the abstract class in file 239, tsc writes a real class with its variable, its constructor and its complete function, and leaves the four abstract methods out:

JavaScript
class BaseTest {
    testName;
    constructor(testName) {
        this.testName = testName;
    }
    loan1() {
        console.log("Loan Given already!");
    }
}

The README's table adds that neither can be created with new, and that a class can implement many interfaces but extend only one class.

11

An interface is just rules

Two panels on cream paper with the same plain room: a small table in front, a curtain on a rail behind it. Left, titled The rules, with the sublabel the interface: the curtain is open, and behind it stands a tall board with five ticked rows, a stopwatch, an open notebook and a laptop; the table is empty. Right, titled What they see, with the sublabel the class: the curtain is closed, the board is only a faint dashed outline on it, and on the table lies one finished folder tied with a terracotta ribbon, with an empty chair facing it.
The interviewer sees only the class; the interface that gave the rules stays hidden.

An interface is just a rule, the instructor said, and told it as a story. The instructor is like an interface, a learner is the class that implements it, and then there is an interviewer. The interface enforces its functions: do the tests, the doubt sessions, the live coding and the coding exercises. The learner has to do all of them. In front of the interviewer, will the learner mention the instructor? Never: that part is completely omitted.

The same thing happens with a class and an interface. The interface puts rules on the class, by giving it incomplete functions that the class has to follow. But when you look at the class, you see only the class: the interface is totally hidden. This is the real abstraction, the instructor said: the interface gives you rules which you have to follow, and it is erased in the JavaScript output.

Why is it erased in the compilation, a learner asked? Because interfaces are just about rules, the instructor said. Every morning when you wake up, you brush your teeth. Someone taught you that, but when you pass it on, do you mention it? No, and you do not write it down anywhere: these are rules that were already given to you.

An abstract class, in contrast, is a real class, incomplete in nature, which exists in the compiled code too. That is why people prefer to use interfaces for the rules, the instructor said. Abstraction is all about rules, and you can achieve a rule with an abstract class or an interface; since an interface is just rules for TypeScript, with zero JS output, why not use that? In Playwright, the abstract class is something we will use very, very rarely, even in the framework; mostly, the concept used is the interface. In Playwright frameworks, the instructor said, we never, never, never try to use an abstract class; we will always use interfaces, and interfaces with normal classes are the best combination. If you want to force rules on a class, create an interface first, and then a class which follows the rules.

Most of these OOP concepts will come back with Playwright, the instructor said: first the bare minimum, with simple examples, then the real examples. Can we have multiple inheritance with interfaces, a learner asked? The instructor thinks it was discussed in an earlier example, and you will see upcoming examples too. By the README's table, a class can implement many interfaces.

12

Running a TypeScript file

How do you run your TypeScript code? You can run it through the command line too, with tsx, the instructor said, who thinks this was already shown. The deck writes the command as npx tsx 211_ENUM.ts, a file this repo does not have; for file 233 it is:

Terminal
npx tsx 33_OOPs_Generic/233_Generic_Method.ts

While files were run in class, errors came up. "Cannot find the name" was passed over. "Unable to compile" was put down to the instructor's own computer: a missing TypeScript configuration, Node.js folders that had been deleted, and a code runner setting. "This is my problem", the instructor said, and for you it will not be a problem. Either you compile the file or you run the TS file directly, the instructor said.

The README gives two more ways: Node 22 by itself, or tsc first. The same file, three ways:

Command File 233 as it is With line 6 switched on
tsx 33_OOPs_Generic/233_Generic_Method.ts prints the three lines prints the three lines: the types are not checked
node 33_OOPs_Generic/233_Generic_Method.ts the same the same
tsc -p ., then node 33_OOPs_Generic/233_Generic_Method.js the same tsc reports TS2345

Of the three, only tsc checks the types: tsx and Node run the file without looking at them. To see the type errors on this page, run tsc -p ..

13

The Playwright page: a tour

Enough of the concepts of JavaScript and TypeScript, the instructor said: now it is time to jump into the real world of Playwright, start coding and use all the concepts. Please note down and bookmark this page, the instructor said; the deck has its address: app.thetestingacademy.com/playwright. It has everything, and you do not have to go anywhere. In Playwright fundamentals, click on Overview: this is where the class is starting. The tour, in the order it was shown; the names of the pages are the site's own:

Part of the page What was shown
Playwright fundamentals: Overview how Playwright works, with interactions; a proper diagram; the CDP protocol; the libraries; fixtures and other concepts
Tables and forms, as example pages Multiple Element Filter, Web Table Directory, QA Profile Form (a form to submit, with multiple checkboxes), Companies Table (dynamic tables), Tall Buildings Table, Custom Dropdowns, Select Box Variants, Sortable Admin Table (with pagination), Cricket Scorecard (a favourite question of the interviewers)
Frames Frames overview (multiple types of frames), Multi-frame frameset
Widgets SVG locators, Shadow DOM, Calendar / date picker, Drag and drop (the Kanban view, a favourite question), Toasts and notifications, Native dialogs (JavaScript dialogs, stacked and custom modals), Hover menus, Right-click menu, Keyboard navigation, Windows and Tabs (with window switching), Upload and Download, Scroll
Assertions (expect) how many types of assertions exist
Test modifiers, hooks, data how to use hooks in Playwright
Network interception if you want to work with APIs
First project: TTACart demo a proper end-to-end cart: add to cart, check out, fill in your information, order, and get the thanks for the order
Second project: TTAStays booking a booking.com clone, a very favourite question of interviewers nowadays
Third: Advance Playwright framework the framework, which covers all the scenarios done; building it, complete, in the end is the ultimate goal
Playwright API Testing CRUD operations, then authentication and schemas (authentication versus authorization), then network monitoring
Playwright BDD (Cucumber) for people who also want to have BDD (see the announcements below)
Playwright AI the AI layer, the new part: five-plus AI agents are going to be added, among them failure analysis, self-healing, prompt to spec, a PR reviewer and a smart generator, with more in the end
TTA AI Chat sandbox a chatbot, because you are going to test chatbots: asked for the test case for the login page in two lines, it gave the answer. Chatbot automation is to be done with Playwright too
Playwright CLI, Playwright MCP and AI agents a few other things, added too (see the announcements below)
Playwright DevOps NPM Registry (JFrog/Nexus) and Sharding multi-container: very advanced, not for everyone, and to be seen in upcoming lectures

But the main motive is to create the advanced automation framework, the instructor said, and the next one month will be very, very interesting.

14

Questions at the end: Markdown files, agents and skills

What is the purpose of an .md file? It is used for instructions or prompts, the instructor said: Markdown files are used to share information from one agent to another, or to note something down or share it.

Is an .md file itself an agent? No, it is an instruction. An agent is created in a proper programming language; the .md file is an instruction that a certain agent reads, and that agent performs the task for you. Real agents are created with LangGraph or LangChain, the instructor said.

What is the difference between RICE-POT and a skill? RICE-POT is a prompt framework, from the 2 October notes; a skill is read by an AI agent, for repurposing. Inside a skill, you can have a RICE-POT too, the instructor said.

15

Tasks and announcements

  • Homework, before the next class. Complete all the GitHub exercises up to 239 and upload them to GitHub: the instructor does not want anyone who is still remaining with this. And set up the Playwright folder too, in a new repo; the instructor will recap it. The deck's closing list has both. The 11 November notes have npm init playwright, step by step.
  • JavaScript test: finish it if you have not, the instructor said, because the class is entering Playwright and everyone should finish the JavaScript too. The instructor thinks there will be one more test on JavaScript, "part 3 or something, part 2 or something", so soon you will have JavaScript part 1 and part 2.
  • Next class: it starts directly with Playwright, and setting it up: installation and everything. The instructor thinks it is already set up somewhere, in the 24th one, and the class will start from there: in the repo, that is the 24_Playwright folder.
  • Playwright notes: the notes to be used for Playwright were shared in class, and the deck's section for this class has their link. The list of notes, edited on screen, now has JavaScript notes, Playwright notes, the GitHub repository, QA battle and interview questions.
  • Interview questions are already up, and you are free to discuss them; a discussion of interview questions and answers will probably come in between.
  • Self-paced, not live: Playwright MCP, Playwright AI agents and the Playwright CLI, already covered; live, they would take a lot of time. The recordings are in the SDET Masterclass, as the deck writes it, with the Selenium to Playwright guide: search for them there.
  • Cucumber is self-paced too: there are sessions to watch, part one and part two. Cucumber BDD will be added in the end, not right now, and is not given directly: if somebody wants it, it is on demand, by asking Meeti.
  • Recap sessions: there will be extra recap sessions in January, February or March, the instructor said, perhaps "biweekly sessions or something", and the batch will be invited. The instructor thinks Cucumber will be covered in February again; "all these five" self-paced topics are going to happen again in February and March, and you can attend them live if you want.
  • Biweekly AI classes: there are none, the instructor told a learner.
  • Access to the academy stays after the course, for a lifetime, and so do the recordings.
  • The code: "I'm pushing all the code now," the instructor said, before the homework. Files 233 to 235 are in the repo's 33_OOPs_Generic folder, 236 to 238 in 34_private_public_protected and 239 in 35_TS_Abstract_Class. The same commit renamed 20 November's 231.API.ts to 232.API.ts, so that lesson numbers are unique.

Task. Before the next class: complete all the GitHub exercises up to 239, upload them to GitHub, and set up the Playwright folder in a new repo.

In a child class such as UserAPIClient, can we use the parent's private variable? The public one? The protected one?

Worth practising too: What does T stand for in a generic, and does it have to be called T? Why not just use any? What does the ! in result[0]! do, and what does an empty array give? Can a class outside, in the same folder, call a protected method? What does readonly allow, and what does it refuse?

Show the answer

Answer. Private, no: this.apiKey in the child is TS2341. Public, yes, and protected, yes: getUsers() uses both baseURL and timeout. T is a placeholder for the actual type, filled in at the call; any name works, and T is used so that everyone recognizes it. any takes any type too, but nothing is checked: let first: string = getFirstAny([200, 400, 500]); gives no error, although first then holds a number, while with getFirstResult<number> it is TS2322. The ! tells the compiler that the value is there, and checks nothing at run time: an empty array gives undefined, with no error. No: only the class and its child classes may use a protected member, whatever folder they are in, so base.navigate("/cart") in NotAPage is TS2445. A readonly field can be set in the constructor; any later change is TS2540, even inside its own class.

What is an abstract class? Can it have an instance variable, a constructor and a complete function? And what is the important difference between an abstract class and an interface?

Show the answer

Answer. A class with incomplete functions, marked abstract, which every child class must write, or tsc reports TS2515. It can have all three: an instance variable, a constructor, and complete functions such as loan1() next to the incomplete ones; it cannot be created with new (TS2511). An abstract class is a partial base, with bodies, a constructor and public, protected or private members, used with extends, and it exists in the compiled JavaScript. An interface is a pure shape: no bodies, no constructor, all members public and abstract, used with implements, and tsc writes nothing for it. A class can implement many interfaces but extend only one class.