Search code examples
typescriptaccess-modifiersprivate-members

How to access private property (with prefix # syntax) in TypeScript


How do I acccess private property of a class denoted by prefix # symbol in TypeScript. I need it for unit testing.

class A {
    #pr: number;
    pu: number
    constructor(pr: number, pu: number) {
        this.#pr = pr;
        this.pu = pu;
    }
}

let a = new A(10, 9);

console.log(a.pu, a.#pr);

Tried this, console.log(a.pu, a["#pr"]); but no success.


Solution

  • There is currently no way to access or even detect the use of (non-polyfilled) private fields. That makes them hard-private.

    You can read some of the reasoning in this proposal discussion.