Skip to content

BUG: getters, setters and inheritance #13432

Closed
@endel

Description

@endel

TypeScript Version: 2.1.4

Code

class Base {
    _height: number;
    public set height (value: number) {
        this._height = value;
    }
}

class Intermediary extends Base {
    public get height () {
        return this._height;
    }
}

class Concrete extends Intermediary {
    constructor () {
        super();
        this.height = 10;
    }
}

let c = new Concrete();
console.log(c.height);

Expected behavior:

Should output 10.

Actual behavior:

  • TypeScript error: "Cannot assign to 'height' because it is a constant or a read-only property."
  • Generated JavaScript file outputs undefined.

The problem here is that the Intermediary class is overwriting the set method. I've changed the output .js file to fix this issue, and it looked like this: (using getOwnPropertyDescriptor on parent's prototype to keep the set reference.)

var Intermediary = (function (_super) {
    __extends(Intermediary, _super);
    function Intermediary() {
        return _super.apply(this, arguments) || this;
    }
    Object.defineProperty(Intermediary.prototype, "height", {
        set: Object.getOwnPropertyDescriptor(_super.prototype, "height").set,
        get: function () {
            return this._height;
        },
        enumerable: true,
        configurable: true
    });
    return Intermediary;
}(Base));

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already createdWorking 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