Typescript polymorphism

11,406

Solution 1

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.

Solution 2

Methods in JS (and TS) are attached to a prototype which is attached to each instance (something like a virtual method table). When you call a method, the actual function is retrieved from the instance's prototype chain rather than the known type of the object. The closest equivalent I'm aware of are virtual methods in C++.

In code:

let greeter = new Ge('world');
// You expect:
Greeter.prototype.greet.call(greeter);
// JS actually does:
greeter.prototype.greet.call(greeter);

Solution 3

I think you misunderstand casting. It's not a "convert into" but more a "interpret as". It basically gives the compiler a hint, wich type/interface he is dealing with, and therefore wich properties and methods are available. It doesn'n say anything about the implementation of these methods, only their signature (wich types go in, wich type comes out)

Share:
11,406
johni
Author by

johni

Updated on June 04, 2022

Comments

  • johni
    johni about 2 years

    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?

  • johni
    johni almost 8 years
    How would I achieve that then?
  • johni
    johni almost 8 years
    How would I achieve that then?
  • ssube
    ssube almost 8 years
    If you want to call the super method on the child, you can directly reference it using the Class.prototype.method syntax and Function's call method.
  • johni
    johni almost 8 years
    I see your point. But that is a bit misleading, don't you agree?
  • Thomas
    Thomas almost 8 years
    Sry, I'm on the phone, can't properly hilight code: Greeter.prototype.greet.call(greeter) to call the method greet from the Greeter class on the instance greeter