TypeScript has three access modifiers, public (the default), protected and private, but only the compiler checks them. At runtime they are erased, and real privacy comes from #field. In a Page Object the page field is made private so tests do not pull selectors into themselves, and parameter properties shorten the constructor but generate code, so they conflict with erasableSyntaxOnly.
TypeScript · Classes
A test calls login.page.locator(...) directly. There is a Page Object and the selectors are still in the tests. What is wrong with the modifiers?
In a Page Object the page field is declared public because it makes the constructor short. A week later the tests contain calls like login.page.locator('button.btn-primary'), and the class no longer hides selectors: after a markup change dozens of tests need fixing. This lesson covers what access modifiers actually do, what they do not guarantee, and how to use them for Page Object discipline.
How it works and why. TypeScript has three access modifiers. public is the default and allows access from anywhere. protected opens a member to the class and its subclasses. private allows only code inside the class. The compiler checks all three and erases them during transpilation: nothing remains in the generated JS, and a private field is an ordinary object property. This follows from TS design: the type system adds nothing to the runtime. Real runtime privacy comes from the JavaScript syntax #field.
Where privacy applies
Figure 1. private, protected and readonly exist only for the compiler, while #field is protected by JavaScript itself.
classTokenStore {
private token = 'a';
#secret = 'b';
}
const store = newTokenStore();
console.log(Object.keys(store)); // ['token']: private shows at runtime
console.log(store['token']); // compiles: bracket access skips private// store.#secret; // SyntaxError outside the class
For a Page Object this is usually enough: the goal is not to protect against an attacker but to nudge the test author toward the right API. So locator fields are made private, and what the test needs stays public. The decision for # is worth considering where privacy matters at runtime: for example a wrapper class over a token that must not end up in JSON.stringify or a report.
Parameter properties. The form constructor(private readonly page: Page) {} declares a field and assigns the argument to it at once. It shortens two lines and is the reason a Page Object constructor is often empty. One nuance: this form generates assignment code, so since TypeScript 5.8 the option erasableSyntaxOnly forbids it (together with enum and namespace that contain code). The option is needed when Node runs the files through built-in type stripping, which only erases annotations. In an ordinary Playwright project parameter properties work without limits, so there is no reason to turn the option on.
The test passes, but LoginPage here is just a bag holding page. The selector button.btn-primary is tied to a CSS class and lives in the test, not in one place. When the markup changes, every test that repeats it breaks, and the class that was supposed to hide it knows nothing.
The fix: close page and expose business actions and the locators needed for expect.
Now the compiler will not allow login.page from a test. Whoever wants a new action has to add a method to the class, where the selector ends up in one place. error stays public because the test checks it with expect.
What a Page Object exposes
Wrong
public page
Tests look for elements through login.page themselves. Selectors spread, the class encapsulates nothing.
Right
private page, actions and locators out
The selector is in one place. The test uses actions and checks public locators.
Figure 2. An access modifier is a contract between a class and the tests.
Limits and alternatives.
private can be bypassed: obj['token'] compiles, and a cast to any removes the check. For ordinary code that is by design, but it is not a security guarantee.
#field is incompatible with some techniques: it is invisible to Object.keys, mocks and Proxy do not see it, and bracket access does not work. For a Page Object this is usually excessive.
readonly is compiler-only as well: a readonly field can be assigned in the declaration or in the constructor. At runtime the property can change.
An alternative to classes: a factory function with a closure, where "private" is just local variables. Suitable for small helpers.
Common mistakes.
public page in a Page Object: tests pull selectors to their side.
Making private the locators a test has to check in expect: extra "isErrorVisible" methods appear.
Treating private as data protection: a token in a private field still appears in console.log and serialisation.
Turning on erasableSyntaxOnly in a Playwright project without need and breaking parameter properties.
Check yourself
A test calls login.page.locator('.err'), the page field is declared private, and still the code works at runtime if the compiler is bypassed. Why?
Answer
Because private is checked by the compiler only and erased during transpilation. At runtime it is an ordinary property. Real privacy comes from #page; access to it outside the class is a SyntaxError.
Why does constructor(private readonly page: Page) {} have an empty body, and why does TS 5.8 have an option that forbids it?
Answer
It is a parameter property: a field declaration and an assignment at once. Because it generates code instead of simply being erased, the option erasableSyntaxOnly forbids it for environments that run TS through type stripping.
Related lessons: “abstract, implements and inheritance in a Page Object”, “The this trap and arrow methods”, “readonly and immutability”.
In an interview.Junior:public, protected and private are checked by the compiler only, and there is no privacy at runtime. In a Page Object I make actions and locators for assertions public and hide page. Middle/Senior: For runtime privacy I use #field, but in a Page Object it is usually excessive: the goal is that tests do not pull selectors to their side. Parameter properties are handy but generate code, so they conflict with erasableSyntaxOnly.
abstract, implements and inheritance in a Page Object
An abstract class cannot be created with new and forces subclasses to implement its abstract members. The implements keyword only checks conformance to an interface and inherits nothing. A base class constructor runs before the subclass fields are initialised, so it must not read them. In a Page Object keep at most one level of base class and compose the page from components passed in through fixtures.
TypeScript · Classes
A base class reads a path that a subclass sets and gets undefined. Why, and why use inheritance in a Page Object at all?
In a Page Object it is handy to move shared behaviour to a base class: open the page, wait for it to load. Subclasses set only their own path. All is well until the hierarchy grows: BasePage, then AuthorizedPage, then DashboardPage, then AdminDashboardPage, and a change at the second level breaks everyone. This lesson covers abstract, implements, initialisation order, and where inheritance works in a framework and where composition is better.
How it works and why. An abstract class cannot be created with new: it holds shared logic and declares abstract members without a body that every descendant must implement. The compiler will not let a descendant exist unless it implements all abstract members. The keyword implements does something else: it checks that a class conforms to an interface but inherits nothing and generates nothing. The interface disappears after compilation, and structural typing already lets any object of the right shape be substituted, so implements is useful only as an early message about a mismatch inside the class itself.
The open() method in the base class runs the shared scenario, and a descendant supplies the specifics through path and waitForLoaded(). This is the classic template method. The override keyword together with the noImplicitOverride option (TS 4.3) forces overrides to be marked explicitly, and renaming a method in the base class breaks the build instead of quietly producing a new method.
Initialisation order: a trap. In JavaScript the base class constructor runs before the subclass fields are initialised. If the base constructor reads this.path directly or indirectly, the field is still empty. TypeScript forbids direct access to an abstract property in a constructor but does not see it through a helper method.
The problem is that each level adds implicit dependencies: AdminDashboardPage inherits a login method it does not need, and a change in AuthorizedPage touches every class below. A new trait ("a page with a header") can only be added as one more level, because there is no multiple inheritance.
The fix: assemble a page from components and hand it to tests through a Playwright fixture (that is how the documentation hands a Page Object to tests).
Now the header is a separate class that can be attached to any page, and the dependencies are visible in the constructor. A shared base class stays when it is truly single and thin.
Hierarchy or composition
Wrong
Three or four inheritance levels
A change at a middle level touches everyone. New traits have to be built in as a new level.
Right
Components and fixtures
A page is made of Header, Table, Form. Dependencies are visible, shared things travel through fixtures.
Figure 2. Inheritance for "is a kind of", composition for "has as a part".
implements for interchangeable implementations. A useful case: two classes with one contract, a real one and a stub.
A test takes PaymentsGateway and does not know which implementation is under it. If a method is added to the interface, both classes stop building.
Limits and alternatives.
One level of base class is fine, three is a signal to refactor.
static members belong to the class, not an instance. For constants and factories they fit. Static state is shared between tests of one worker (each Playwright worker is a separate process with its own module), and a test that changes it affects the next tests of that worker, hence flakiness.
A base can be not a class but a set of helper functions or a mixin if only shared behaviour is needed.
Library classes such as Playwright's Page are usually not extended but wrapped in a class of your own.
Common mistakes.
Reading in a base class constructor a property that the subclass sets: you get undefined.
Building deep Page Object hierarchies: a change at the top breaks everything below.
Treating implements as inheritance: code from an interface does not enter the class.
Keeping test state in static: it lives as long as the worker.
Check yourself
In BasePage the constructor calls this.logOpen(), which prints this.path, and AccountsPage sets path = '/accounts'. The console shows undefined. Why?
Answer
The base class constructor runs before the subclass fields are initialised, so path is not assigned yet. Work that depends on subclass fields is done later in a method, not in the base constructor.
How does implements differ from extends, and what happens if a method is added to the interface?
Answer
extends inherits code, implements only checks conformity with an interface and adds nothing. If a method is added to the interface, every class with implements that lacks it stops building.
Related lessons: “Access modifiers and parameter properties”, “Generics in Playwright: fixtures”, “interface or type”.
In an interview.Junior: An abstract class gives shared logic and forces descendants to implement the needed methods, while implements only checks a contract. Middle/Senior: In a Page Object I keep at most one level of base class and prefer composition from components passed through fixtures. I remember the initialisation order: the base constructor runs before the subclass fields, so I do not read subclass fields in it.
The this trap and arrow methods
In JavaScript this depends on how a function is called, so a method passed as a callback loses its object. In strict mode this becomes undefined, as in retry(login.open). The fixes are a wrapper () => login.open(), bind or an arrow property, which is created per instance and does not work with super. The compiler does not catch this, so enable the ESLint rule unbound-method.
TypeScript · Classes
retry(login.open) fails with "Cannot read properties of undefined" while login.open() works. What changed?
A retry helper accepts a function, and the author passes it a Page Object method: retry(login.open). The method looks perfectly normal in the class, TypeScript underlines nothing, and at run time a TypeError appears inside the method. The same method called as login.open() works. This lesson is about why this in JavaScript depends on the call, and how to fix it without surprises.
How it works and why. In JavaScript the value of this inside an ordinary function is determined not by where it was declared but by how it was called. When you write login.open(), the object before the dot becomes this. When the function is put into a variable or passed as an argument, the link to login is lost: the call fn() goes without an object. Class methods live on the prototype and are not bound to an instance, and a class body runs in strict mode, so this becomes undefined instead of the global object, and this.page fails.
asyncfunction retry<T>(fn: () => Promise<T>, times = 3): Promise<T> {
for (let i = 1; ; i++) {
try {
returnawaitfn();
} catch (e) {
if (i >= times) throw e;
}
}
}
classLoginPage {
constructor(privatereadonly page: Page) {}
asyncopen() {
awaitthis.page.goto('/login');
}
}
const login = newLoginPage(page);
awaitretry(login.open);
// TypeError: Cannot read properties of undefined (reading 'page')awaitretry(() => login.open()); // works
Where this comes from
Figure 1. One method, three ways to call it, three different values of this.
Why the compiler is silent. The type of login.open is just () => Promise<void>: for ordinary class methods TypeScript does not track that a function waits for a particular this, and accepts it wherever the signature fits. A method can be detached accidentally too, for example in array.map(helper.format).
The wrapper() => login.open() is simplest: the call goes through a dot again, and this is right. bind creates a new function with a fixed this; in TypeScript under strictBindCallApply it keeps the types. An arrow propertyopenArrow = async () => … captures the instance this when the object is created, so it can be passed anywhere.
An arrow property has a cost. It is created separately for each instance and does not live on the prototype, so it takes memory per instance. A subclass cannot call it through super.openArrow() because the prototype has no such function. It cannot be mocked or replaced through the prototype. For a Page Object, with few instances, this is usually acceptable, and such a method is rarely passed as a callback.
A method or an arrow property
Ordinary method
Wrapper or bind
One function on the prototype, works with super and mocking. When passing it, this must be bound.
Arrow property
Captures this
Can be passed as is. A separate function in each instance, super does not work.
Figure 2. Both options are legitimate: the choice depends on how the method is used.
How to prevent it. TypeScript can require an explicit this: a this: Foo parameter in a function signature forbids a call without the right context. For ordinary methods a more useful tool is the ESLint rule from typescript-eslint that catches passing an unbound method:
The rule unbound-method needs a type-checked configuration and flags a reference to a class method without a call. Arrow properties and bound functions are not touched by it.
Limits and alternatives.
An arrow function has no this of its own: it takes it from the surrounding scope. So inside a class method () => this.x is safe.
The problem is not only about classes: a method of a plain object { read() { return this.v } } behaves the same way.
An alternative: do not rely on this at all and write a Page Object as a set of functions with a closure.
Before passing a library method (not your own class's) as a callback, check in the documentation whether it depends on this: otherwise the behaviour is not guaranteed.
Common mistakes.
Passing obj.method as a callback (to retry, map, setTimeout): this is lost.
Making all methods arrow properties "just in case": they lose super and the prototype.
Relying on the compiler to catch it: without an ESLint rule it does not.
Confusing bind with a call: fn.bind(obj) only returns a new function, and only the next call runs it.
Check yourself
Why does retry(login.open) fail while retry(() => login.open()) works, though the method is the same?
Answer
In the first case retry calls the function without an object before the dot, so this is undefined (a class body is strict). In the second the call goes as login.open() and this is login.
What is the cost of an arrow property open = async () => … instead of an ordinary method?
Answer
The function is created separately for each instance and is not on the prototype, so a subclass cannot call it through super.open() and it cannot be replaced through the prototype. In return this is always right.
Related lessons: “Access modifiers and parameter properties”, “abstract, implements and inheritance in a Page Object”, “Promise, async/await and a forgotten await”.
In an interview.Junior:this in JavaScript depends on how a function is called, so a method passed as a callback loses its context. I pass an arrow wrapper or use bind. Middle/Senior: The compiler does not catch this, so I turn on the ESLint rule unbound-method and watch for it in review. I use an arrow property selectively: it guarantees this, but it is created per instance and does not work with super.