QA Interview Hub · Knowledge base · Quizzes · Українська

TypeScript › Classes and access modifiers

Access modifiers and parameter properties

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

public, protected, privatechecked by tsc, no trace in JSreadonlycompile time only: assign in the constructor#fieldprivate at runtime too, SyntaxError outside
Figure 1. private, protected and readonly exist only for the compiler, while #field is protected by JavaScript itself.
class TokenStore {
  private token = 'a';
  #secret = 'b';
}

const store = new TokenStore();
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.

Example: a class that hides nothing.

export class LoginPage {
  constructor(public page: Page) {}
}

test('empty form shows an error', async ({ page }) => {
  const login = new LoginPage(page);
  await login.page.goto('/login');
  await login.page.locator('button.btn-primary').click();
  await expect(login.page.locator('.err')).toBeVisible();
});

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.

export class LoginPage {
  readonly error: Locator;
  private readonly submit: Locator;

  constructor(private readonly page: Page) {
    this.submit = page.getByRole('button', { name: 'Sign in' });
    this.error = page.getByRole('alert');
  }

  async open() {
    await this.page.goto('/login');
  }

  async submitEmpty() {
    await this.submit.click();
  }
}

test('empty form shows an error', async ({ page }) => {
  const login = new LoginPage(page);
  await login.open();
  await login.submitEmpty();
  await expect(login.error).toBeVisible();
});

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.

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.

More articles in this chapter