See the inheritance example from the playground on the TypeScript site:
class Animal {
public name;
constructor(name) {
this.name = name;
}
move(meters) {
alert(this.name + " moved " + meters + "m.");
}
}
class Snake extends Animal {
constructor(name) {
super(name);
}
move() {
alert("Slithering...");
super.move(5);
}
}
class Horse extends Animal {
constructor(name) {
super(name);
}
move() {
alert(super.name + " is Galloping...");
super.move(45);
}
}
var sam = new Snake("Sammy the Python");
var tom: Animal = new Horse("Tommy the Palomino");
sam.move();
tom.move(34);
I have changed one line of code: the alert in Horse.move(). There I want to access super.name, but that returns just undefined. IntelliSense is suggesting that I can use it and TypeScript compiles fine, but it does not work.
Any ideas?
Working example. Notes below.
You don’t need to manually assign the name to a public variable. Using
public namein the constructor definition does this for you.You don’t need to call
super(name)from the specialised classes.Using
this.nameworks.Notes on use of
super.This is covered in more detail in section 4.9.2 of the language specification.
The behaviour of the classes inheriting from
Animalis not dissimilar to the behaviour in other languages. You need to specify thesuperkeyword in order to avoid confusion between a specialised function and the base class function. For example, if you calledmove()orthis.move()you would be dealing with the specialisedSnakeorHorsefunction, so usingsuper.move()explicitly calls the base class function.There is no confusion of properties, as they are the properties of the instance. There is no difference between
super.nameandthis.name– there is simplythis.name. Otherwise you could create a Horse that had different names depending on whether you were in the specialized class or the base class.