Typescript polymorphism
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)
johni
Updated on June 04, 2022Comments
-
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 transpiledJavascript
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 almost 8 yearsHow would I achieve that then?
-
johni almost 8 yearsHow would I achieve that then?
-
ssube almost 8 yearsIf you want to call the super method on the child, you can directly reference it using the
Class.prototype.method
syntax and Function'scall
method. -
johni almost 8 yearsI see your point. But that is a bit misleading, don't you agree?
-
Thomas almost 8 yearsSry, 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