Skip to content

private fields are not private #564

Closed
@reverofevil

Description

@reverofevil

Consider the following code

export class Test {
    private x: number;
    constructor() {
        this.x = 42;
    }
    f() : number {
        return this.x;
    }
}

Typescript generates the following JS

var Test = (function () {
    function Test() {
        this.x = 42;
    }
    Test.prototype.f = function () {
        return this.x;
    };
    return Test;
})();
exports.Test = Test;

Obviously, one could run something like new Test().x in a JS library, and private invariant would fail. I think it's not a kind of behaviour one would expect from private, at least in exported classes. The fix is quite simple:

var Test = (function () {
    var _private = {};
    function Test() {
        _private.x = 42;
    }
    Test.prototype.f = function () {
        return _private.x;
    };
    return Test;
})();
exports.Test = Test;

Metadata

Metadata

Assignees

No one assigned

    Labels

    By DesignDeprecated - use "Working as Intended" or "Design Limitation" instead

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions