Last updated: Mar 2, 2024
Reading timeยท2 min
The "Private field must be declared in an enclosing class" error occurs when we try to read a private value directly from our code outside of the class object.
To solve the error, make sure to only read private values from inside of the class.
Here's an example of how the error occurs.
class Person { #num = 100; } const p = new Person(); // โ๏ธ Private field '#num' must be declared in an enclosing class console.log(p.#num);
We got an error because we tried to access a private value directly in our code, outside of the class.
#
) are accessible on the class constructor from inside the class declaration.Make sure you don't try to set private fields inside of the constructor()
function of your class without having initialized them in the body of the class.
Make sure to only access private fields from inside the class.
class Person { // ๐๏ธ Private field #num = 200; // ๐๏ธ Another private field #another_private; constructor(first, last) { this.first = first; this.last = last; this.#another_private = 'another private field'; } getAnother() { return this.#another_private; } getNum() { // ๐๏ธ Accessing private field return this.#num; } getName() { // ๐๏ธ Calling private method return this.#fullName(); } // ๐๏ธ Private Method #fullName() { return `${this.first} ${this.last}`; } } const p = new Person('Bobby', 'Hadz'); console.log(p.getName()); // ๐๏ธ "Bobby Hadz" console.log(p.getNum()); // ๐๏ธ 200 console.log(p.getAnother()); // ๐๏ธ another private field
We declared a private field #num
and a private method #fullName
.
Notice that we initialized the another_private
field in the body of the class
before setting it in the class's constructor method.
We can access the private fields and methods from inside the scope (inside of the class), but if we try to access them directly from our code, we will get the error.
You can also initialize a private field without a value and set its value at a later point.
class Person { // ๐๏ธ Private field #num; increment() { this.#num = typeof this.#num === 'number' ? this.#num + 100 : 100; return this.#num; } } const p = new Person(); console.log(p.increment()); // ๐๏ธ 100 console.log(p.increment()); // ๐๏ธ 200 console.log(p.increment()); // ๐๏ธ 300
We declared a private field #num
without initializing its value. Note that a
private field can only be defined once in a single class.