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?
Polymorphism is the ability to create a class that has more than one form. Or in other words, classes have the same methods but different implementations.
Implement polymorphism in TypeScriptWhen multiple classes inherit from a parent and override the same functionality, the result is polymorphism. Each of those child classes now implements a property or method, but they each may have their own way of performing that implementation.
In TypeScript, we can use common object-oriented patterns. One of the most fundamental patterns in class-based programming is being able to extend existing classes to create new ones using inheritance.
Inheritance is one in which a new class is created (derived class) that inherits the features from the already existing class(Base class). Whereas polymorphism is that which can be defined in multiple forms. 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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With