Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) {
        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?

like image 748
johni Avatar asked Aug 22 '16 14:08

johni


People also ask

What is Polymorphism in TypeScript?

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.

Can we use Polymorphism in TypeScript?

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.

Is TypeScript OOP based?

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.

What is difference between Polymorphism and 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.


2 Answers

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);
like image 168
ssube Avatar answered Oct 02 '22 21:10

ssube


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.

like image 30
Justin Niessner Avatar answered Oct 02 '22 20:10

Justin Niessner