johni johni - 1 year ago 271
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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download