Typescript polymorphism

Please look at 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 expect the second magazine to print Hello, world. Looking at the code passed Javascript, I see the same command so that this is not a surprise.

The real question is: how do you add greeterto your extended class?

+4
source share
4 answers

You have already made a greeterparent class.

The override method in a class does not change the behavior when casting as a parent.

+3
source

JS ( TS) , (- ). , , . , , - virtual ++.

:

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

, . " ", " ". , , , , . , ( , )

+2

Casting , .

JavaScript, . , , A, B., JavaScript .

greet, ( ). , .

, , , , .

0

Source: https://habr.com/ru/post/1652076/


All Articles