johni johni - 3 months ago 46
TypeScript Question

Typescript polymorphism

Please have a look on this code:

class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}

class Ge extends Greeter {
constructor(message: string) {
super(message);
}
greet() {
return "walla " + super.greet();
}
}

let greeter = new Ge("world");

console.log(greeter.greet()); // walla Hello, world
console.log((<Greeter> greeter).greet()); // walla Hello, world


I would expect the second log to print
Hello, world
.
Looking at the transpiled
Javascript
code, I see the exact same command so it's not that a surprise.

The real question is, how do you cast
greeter
to its extended class?

Answer

You already did cast greeter to it's parent class.

An overriden method in a class doesn't change behavior when cast as its parent.