Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript derived class cannot have the same variable name?

Tags:

typescript

Why can't typescript derived class have the same variable name? Even these members are private. Is there an alternative to this, or am I doing something wrong?

class ClassTS {
    
    private nom: string = "ClaseTS";
    
    constructor() {
            
    }
}

class ClassTSDer extends ClassTS {
    
    private nom: string = "ClassTS";
    
    constructor() {
        super();
    }
}

I found this while practising with TS.

Class 'ClassTSDer' incorrectly extends base class 'ClaseTS'. Types have separate declarations of a private property 'nom'. ClassTSDer

class ClassTSDer

you could, use protected; yes but if I do not want to use protected, would I have to use another name?

like image 230
Angel Angel Avatar asked Feb 29 '16 20:02

Angel Angel


2 Answers

The properties must have different names.

Remember that at runtime, JavaScript class instances are just objects, and objects are just mappings from key to value. The property names are the key, and you can't have two different keys with the same name.

like image 102
Ryan Cavanaugh Avatar answered Nov 09 '22 21:11

Ryan Cavanaugh


The properties must have different names.

If you'll look at the generated ES5 code you can see that declaring a property on the child class with the same name as a private property as the parent will overwrite the parent one thus breaking encapsulation.

/**
 * ClassTS
 */
var ClassTS = (function () {
    function ClassTS() {
        this.nom = "ClaseTS";
    }
    ClassTS.prototype.someMethod = function () {
        console.log(this.nom);
    };
    return ClassTS;
}());
/**
 * ClassTSDer
 */
var ClassTSDer = (function (_super) {
    __extends(ClassTSDer, _super);
    function ClassTSDer() {
        _super.call(this);
        this.nom = "ClassTS";
    }
    ClassTSDer.prototype.childMethod = function () {
        _super.prototype.someMethod.call(this);
    };
    return ClassTSDer;
}(ClassTS));

In this case for any function from the parent called in the child will result in this.nom having the value "ClassTS" instead of "ClaseTs" as you'd expect from a private property.

The compiler does not complain about the protected properties (even though they generate the same ES5 code) because the expectation of encapsulation is no longer there.

like image 34
toskv Avatar answered Nov 09 '22 21:11

toskv