johni johni - 2 months ago 11
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) {
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
code, I see the exact same command so it's not that a surprise.

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


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.