Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 96 ยท Objects and Classes

Access Modifiers and Private Fields

Control access to class members in TypeScript - public, protected and private vs JavaScript #private fields, static members, getters, setters and the accessor keyword.

A class usually has two audiences: code inside the class, which needs full access to its internals, and code outside, which should only use a small, stable surface. Hiding the internals keeps callers from depending on details you may want to change, and protects invariants such as "the balance is never negative". TypeScript gives you three access modifiers (public, protected and private) and also supports JavaScript's own #private fields. They look similar but work very differently.

This lesson explains both systems and when to pick which, then covers the other members that shape a class's public surface: static members, getters and setters, and the accessor keyword. It builds on Classes; the JavaScript side of private fields is covered in Private and Static Members.

public, private and protected

Every class member is public unless you say otherwise. Writing public explicitly is allowed but rarely needed. The other two restrict where a member can be used:

Modifier Accessible from
public (default) Anywhere
protected The class itself and its subclasses
private Only the class that declares it
TypeScript private and protected members

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Callers can read t.target and call raise(), but they can't set targetCelsius directly or call setTarget(), so the 10โ€“28 limit can't be bypassed. The subclass can read the protected log, but code outside the class hierarchy can't. Try it from outside and you get errors:

TypeScript Accessing hidden members from outside (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Two errors, and nothing runs: main.ts(7,3): error TS2341: Property 'targetCelsius' is private and only accessible within class 'Thermostat'. and main.ts(8,15): error TS2445: Property 'log' is protected and only accessible within class 'Thermostat' and its subclasses.

private is per class, not per object: a method of Thermostat may read the private fields of another Thermostat instance, which is handy for methods like equals(other).

TypeScript private is compile-time only

Here's the catch. private and protected are TypeScript-only: like all type information they're erased, and the emitted JavaScript has ordinary properties. They're "soft" privacy:

TypeScript Soft privacy: private is erased

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The private token shows up when the object is logged, serialized or enumerated, and client['token'] compiles on purpose: TypeScript allows bracket access to private members as an escape hatch (useful in tests). Plain JavaScript code calling your library can read it too, because it never sees the types.

JavaScript #private fields

Modern JavaScript has its own private members: any field, method or accessor whose name starts with #. These are hard private: enforced by the JavaScript engine at runtime, invisible to Object.keys, JSON.stringify and bracket access, and impossible to read from outside the class body, even from plain JavaScript.

TypeScript Hard privacy with #private

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The logged object shows nothing at all, because #balance is not a normal property. Trying w.#balance outside the class is a syntax error in JavaScript and a compile error in TypeScript (TS18013, "Property '#balance' is not accessible outside class 'Wallet' because it has a private identifier."). The #balance in value expression is an ergonomic brand check: it returns true only for objects created by this class, which makes a perfect type guard.

Note that { balance: 25 } fails the brand check even though it has the same public balance property. The type checker agrees: a class with private members (of either kind) doesn't accept look-alike objects, so const fake: Wallet = { balance: 25, deposit: ... } is an error. Private members make a class behave a bit more nominally.

Which one should you use?

private (TypeScript) #private (JavaScript)
Enforced At compile time only At runtime, by the engine
Visible in logs, JSON, Object.keys Yes No
Escape hatch obj['name'] None
Subclasses can redeclare the same name No (error) Yes, they're independent
Works with parameter properties Yes No
Proxy-friendly Yes No (proxies can't forward # access)

Use #private for anything that must really be hidden: security-sensitive data, library internals that JavaScript users must not touch, or invariants you can't afford to have bypassed. Use private when compile-time protection is enough and you value its conveniences, such as parameter properties or easier testing and mocking. Many teams simply pick one style per code base. Both are fully supported.

Static members

static members belong to the class itself, not to instances. You access them through the class name. They're useful for constants, counters shared by all instances, caches and factory methods. Static members can be private, protected, readonly or #private too:

TypeScript Static members, a static block and a private constructor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

A private constructor means new Color(...) only works inside the class, so all creation goes through fromHex, which caches colors. That's how you build factories and singletons. The static { ... } block is plain modern JavaScript for one-time setup. The cast (Color as { BLACK: Color }) is needed because BLACK is readonly and static blocks don't get the constructor's exemption. A static initializer like static readonly BLACK = Color.fromHex('#000000'); would be simpler; the block is here to show the syntax.

Inside a static method, this refers to the class itself, but writing the class name, as here, is clearer. Static members can't use the class's generic type parameters, since there's only one class object for all Ts.

Getters and setters

Accessors let a property read like data while running code. A getter alone makes a read-only property; a setter lets you validate or transform values on assignment:

TypeScript Getters and setters with validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TypeScript infers a property with only a getter as readonly, so the last assignment is error TS2540. The @ts-expect-error comment lets the program compile anyway, and the output shows what happens at runtime: assigning to a getter-only property in a class (always strict mode) throws TypeError: Cannot set property label of #<Rating> which has only a getter. The type error saves you from that crash.

Getters and setters are also a safe way to evolve a class: you can start with a plain public field and later turn it into an accessor pair without changing any callers.

The accessor keyword

TypeScript 4.9 added support for auto-accessors, a part of the standard decorators proposal. accessor name = value; declares a private storage slot plus a public getter and setter for it, in one line:

TypeScript
class Settings {
  accessor theme = 'light';
}
// Roughly the same as:
class SettingsLonghand {
  #theme = 'light';
  get theme() { return this.#theme; }
  set theme(value: string) { this.#theme = value; }
}

On its own, accessor behaves like a normal field. Its real purpose is to give decorators a getter/setter pair they can wrap (for example to log, validate or observe changes), which a plain field doesn't provide. You'll see it in action in the decorators lesson.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A class has private secret = 1;. What does console.log(JSON.stringify(obj)) print for an instance?

    TypeScript's private is erased at compile time, so secret is an ordinary property at runtime and appears in JSON.
  2. 2. Which member can a subclass use, but outside code cannot?

    protected members are visible in the declaring class and its subclasses. private and #private are limited to the declaring class.
  3. 3. What does #token in value return for a plain object { token: 'x' }?

    An ergonomic brand check is only true for objects that really have the class's #token private field; a normal token property doesn't count.
  4. 4. A class has get total(): number but no setter. What happens with cart.total = 5;?

    TypeScript treats a getter-only property as readonly. At runtime, the assignment would throw a TypeError in a class.
  5. 5. Why give a class a private constructor?

    Only code inside the class can call new, so callers must use methods like fromHex() or getInstance(), which can cache or validate.

Summary

  • Members are public by default. protected limits access to the class and subclasses; private to the declaring class. Violations are errors TS2341/TS2445.
  • TypeScript's private/protected are compile-time only: the properties exist at runtime, show in logs and JSON, and obj['name'] is an allowed escape hatch.
  • JavaScript #private members are enforced at runtime, invisible from outside, and support #field in obj brand checks.
  • static members belong to the class: use them for constants, caches and factories; combine with a private constructor and static { } blocks.
  • Getters and setters compute and validate; a getter without a setter is readonly. Setters may accept a wider type than the getter returns (TS 5.1+).
  • accessor declares an auto-accessor (private storage + get/set), mainly as a target for standard decorators.

Next: Inheritance and Abstract Classes