Skip to content

Class private members accessible from outside with brackets notation #19335

Closed
@marcomura

Description

@marcomura

I'm concerned about private members being "legally" accessible from outside the class, since it could lead people to believe it's an acceptable way for doing it in production code.
Currently, my team believes this is an acceptable way for unit testing code.

This approach even detects the correct private member's type, so it's not a workaround to access the raw members through upcast to any...

TypeScript Version: 2.4

Code

class Test {
    constructor(private _x: number) { }
    getValue(): number { return this._x; }
}
let t = new Test(10);
t["_x"] = -6;

Expected behavior:
Compiler error: "Property '_x' is private and only accessible within the class 'Test'".

Actual behavior:
No errors.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions