Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Node.js, PHP and APIs

TypeError: Cannot read private member from an object whose class did not declare it

ErrorTypeError: Cannot read private member #x from an object whose class did not declare it

Short answer

A #private field exists only on objects that the class itself constructed. The error means the code reached for the field on something else. Print this on the failing line. A subclass or a Proxy as this, an event emitter or other caller replacing this, or a plain object passed in each break the brand check, and each has a short fix.

  • Applies to Node.js 22, ECMAScript private class elements
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    The stack trace names the line that reads the private field. Print this on the line just before it. A class (a function) points to the static case, an emitter or other foreign object to a lost this, and an object that looks right but is wrapped points to a Proxy.

    // on the line before the failing #field access
    console.log(this);
  2. 2Match what you see, then jump to its fix

    1. 1The failing method is static, and the call goes through a class that extends the one that declares the fieldA static method that uses this reaches the private static field through a subclassFix
    2. 2The object works when you use it directly, and throws only through a wrapper, mock, spy or reactive layerThe instance is wrapped in a ProxyFix
    3. 3The method works when called as obj.method(), and fails when it is handed to an event emitter, a timer or another APIA method was passed as a callback and the caller replaced thisFix
    4. 4The failing function takes an argument and reads obj.#field, and the argument came from JSON, a spread copy or a test fixtureA plain object or a copy is passed where a class instance is expectedFix

What does the error look like?

  • TypeError: Cannot read private member #x from an object whose class did not declare it
  • TypeError: Cannot read private member #privateStaticField from an object whose class did not declare it

Cause 1 of 4

A static method that uses this reaches the private static field through a subclass

1Check

A private static field belongs to the class that declares it, and to nothing else. When a static method is called as Subclass.method(), this is Subclass, not the parent, so this.#field looks on the wrong class. super calls do not pass the parent as this either.

grep -rn "this\.#" src/

2Fix

Name the declaring class when you read a private static field, and never go through this.

class Pool {
  static #count = 0;
  static opened() {
    return Pool.#count;   // not this.#count
  }
}
class Child extends Pool {}
Child.opened();

3Verify

The call through the subclass returns the value and no longer throws.

node -e "class A { static #n = 42; static get() { return A.#n; } } class B extends A {} console.log(B.get())"

Confirmed by developer.mozilla.org

Did this fix it?

Cause 2 of 4

The instance is wrapped in a Proxy

1Check

A proxy is a different object with its own identity, so it does not hold the target's private elements. Inside a getter or method called through the proxy, this is the proxy. Look for new Proxy in your code or in the helper that wraps the object.

grep -rn "new Proxy" src/ test/

2Fix

Make the trap call the property on the target, so the getter runs with the real object as this. For methods, return a function that swaps the proxy for the target.

const wrapped = new Proxy(instance, {
  get(target, prop, receiver) {
    const value = target[prop];
    if (value instanceof Function) {
      return function (...args) {
        return value.apply(this === receiver ? target : this, args);
      };
    }
    return value;
  },
});

3Verify

Read the property and call the method through the proxy. Both work now.

node -e "class S { #x = 1; x() { return this.#x; } } const s = new S(); const p = new Proxy(s, { get(t, k, r) { const v = t[k]; return v instanceof Function ? function (...a) { return v.apply(this === r ? t : this, a); } : v; } }); console.log(p.x())"

Confirmed by developer.mozilla.org

Did this fix it?

Cause 3 of 4

A method was passed as a callback and the caller replaced this

1Check

Node.js sets this to the emitter for an ordinary listener function. If you pass instance.handler to emitter.on(), this inside it is the emitter, which never declared your private field. Many Node.js objects are event emitters.

grep -rn "\.on(.*this\." src/

2Fix

Wrap the call in an arrow function, which keeps this as the instance, or bind the method to the instance.

class Crawler {
  #seen = 0;
  handle() { this.#seen += 1; }

  attach(emitter) {
    emitter.on('response', () => this.handle());   // arrow function
    // or: emitter.on('response', this.handle.bind(this));
  }
}

3Verify

Emit the event once and confirm that the handler runs without the error.

node -e "const E = require('node:events'); class C { #n = 0; h() { return ++this.#n; } attach(e) { e.on('x', () => console.log(this.h())); } } const e = new E(); new C().attach(e); e.emit('x')"

Confirmed by nodejs.org

Did this fix it?

Cause 4 of 4

A plain object or a copy is passed where a class instance is expected

1Check

If you access a private element on an object that does not have it, you get a TypeError and not undefined. Private elements cannot be enumerated or handled with Object methods, so a plain object made from an instance does not carry them. Only an object built by the class constructor has the field.

grep -rn "\.#" src/

2Fix

Construct a real instance with the class, and where outside objects can reach the code, check the field first with the in operator.

class Money {
  #cents;
  constructor(cents) { this.#cents = cents; }
  static cents(obj) {
    if (#cents in obj) return obj.#cents;
    throw new TypeError('expected a Money instance');
  }
}
Money.cents(new Money(500));

3Verify

A real instance works. A plain object now fails with your own clear message.

node -e "class M { #c; constructor(c) { this.#c = c; } static c(o) { if (#c in o) return o.#c; return 'not a M'; } } console.log(M.c(new M(5)), M.c({}))"

Confirmed by developer.mozilla.org

Did this fix it?

How do I stop it coming back?

  • Read private static fields through the class name, not through this.
  • Register class methods as listeners with an arrow function or bind, and keep one habit across the code base.
  • Give wrapped or mocked objects a get trap that calls through to the target.
  • Use #field in obj before reading a private field from an object that came from outside.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Back end

ng serve says it cannot determine the project or target

Cannot determine project for command.

The Angular CLI looked through angular.json for a project that defines the target you asked for (serve, build, test) and found none, or found several and could not pick one.

3 causes, each with a fix

Back end

ng serve cannot find the dev-server builder package

Could not find the implementation for builder @angular/build:dev-server

The builder named in angular.json (for example @angular-devkit/build-angular:dev-server) is looked up as an npm package starting from the workspace root.

3 causes, each with a fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.