Read or write-only private fields should be accessed properly

  • INVALID_PRIVATE_FIELD_ACCESS
  • Error
  • High
  • es13

This rule applies when read or write-only private fields of a class are not accessed properly.

TypeError exceptions are thrown in the following improper access cases:

  1. A value is assigned to a private field declared as a getter without a corresponding setter.
  2. A value is read from a private field declared as a setter without a corresponding getter.
  3. A private method is updated to another value. Unlike public methods, private methods are not writable. You should use a private field with a function expression instead in this case.

Noncompliant Code Example

View with compliant examples side by side
class Example {
    #firstName;
    #lastName;

    get #fullName() {
        return `${this.#firstName} ${this.#lastName}`;
    }
    set #name(x) {
        const nameParts = x.split(/\s+/);
        this.#firstName = nameParts[0] || '';
        this.#lastName = nameParts[1] || '';
    }
    #isValidName() {
        return this.#firstName !== '' && this.#lastName !== '';
    }

    constructor(fullName) {
        this.#fullName = fullName || ''; // INVALID_PRIVATE_FIELD_ACCESS alarm because only getter is defined for '#fullName'.
        if (!this.#isValidName()) {
            console.log(`${this.#name} is invalid!`); // INVALID_PRIVATE_FIELD_ACCESS alarm because only setter is defined for '#name'.
        }
        this.#isValidName = this.#isValidName.bind(this); // INVALID_PRIVATE_FIELD_ACCESS alarm because private method is read-only.
    }
}

Compliant Code Example

View with noncompliant examples side by side
class Example {
    #firstName;
    #lastName;

    get #fullName() {
        return `${this.#firstName} ${this.#lastName}`;
    }
    set #fullName(x) {
        const nameParts = x.split(/\s+/);
        this.#firstName = nameParts[0] || '';
        this.#lastName = nameParts[1] || '';
    }
    #isValidName = () => this.#firstName !== '' && this.#lastName !== '';

    constructor(fullName) {
        this.#fullName = fullName || '';
        if (!this.#isValidName()) {
            console.log(`${this.#fullName} is invalid!`);
        }
    }
}

Version

This rule was introduced in DeepScan 1.49.0.

See

  • Private class fields

  • Uncaught TypeError: '#fullName' was defined without a setter

  • Uncaught TypeError: '#name' was defined without a getter

  • Uncaught TypeError: Private method '#isValidName' is not writable

Was this documentation helpful?