Inheritance in typescript returns undefined

104 views Asked by At

I'm, writing the below code, I can't understand how it is working. In C# or Java when we use base or super keyword it returns values but in typescript, I'm getting "undefined". If I use "this" instead of "super" it is working.

class Person {
    public firstName: string;
    public lastName: string;

    constructor(fn: string, ln: string) {
        this.firstName = fn;
        this.lastName = ln;
    }
}

class Customer extends Person {

    constructor(fn: string, ln: string) {
        super(fn, ln);
    }

    displayDetails() {
        console.log(`First Name :${super.firstName}\tLast Name :${super.lastName}`);
    }
}

let c = new Customer("Pradeep", "Kumar");
c.displayDetails();

could someone explain the execution?

1

There are 1 answers

0
Lesiak On BEST ANSWER

See relevant docs at MDN: super

The super keyword is used to access properties on an object literal or class's [[Prototype]], or invoke a superclass's constructor.

Note that instance fields are set on the instance instead of the constructor's prototype, so you can't use super to access the instance field of a superclass.