The Ultimate Typescript Guide - Method overriding

I was trying to implement the method overriding from the tutorial video. And I found that when I override the method and try to print the full name from the parent it is returning ‘undefined’.

class Person {
  constructor(public firstName: string, public lastName: string) {}

  get fullName(): string {
    return this.firstName + ' ' + this.lastName;
  }
}

// Inheritence and method overriding
class Teacher extends Person {
  override get fullName() {
    return 'Professor.' + super.fullName;
  }
}

let teacher = new Teacher('John', 'doe');
console.log(teacher.fullName); // prints 'Professor undefined undefined'

Constructors are not inherited in Typescript, so you have to write it out explicitly with the call to the super constructor (also it looks like you probably meant to use a space at the end of “Professor” or else you will get “Professor.John doe” rather than “Professor John doe”).

class Teacher extends Person {
  constructor(firstName: string, lastName: string) {
    super(firstName, lastName);
  }

  override get fullName() {
    return 'Professor ' + super.fullName;
  }
}

With that change, the following logs Professor John Doe (as expected):

const johnDoe = new Teacher('John', 'Doe');
console.log(johnDoe.fullName);

Hi,
I didn’t understand the part “Constructors are not inherited Typescript

Mosh says that the Teacher class inherits the constructor of the Person class which is our base class
because we didn’t add extra properties on Teacher class so when we create an instance of the Teacher class we inherit the constructor of the Person class which IntelliSense shows

1 Like

Hi,
I just copy & pasted your code & it’s working perfectly

You are correct and I just tested this in a Typescript REPL and got the expected results with your original code:

class Person {
  constructor(public firstName: string, public lastName: string) {}

  get fullName(): string {
    return this.firstName + ' ' + this.lastName;
  }
}

class Teacher extends Person {
  override get fullName() {
    return 'Professor ' + super.fullName;
  }
}

let teacher = new Teacher('John', 'Doe');
console.log(teacher.firstName);
console.log(teacher.lastName);
console.log(teacher.fullName);

Prints

John
Doe
Professor John Doe

In fact, copying and pasting your original code into a Typescript REPL prints the following for me:

Professor.John doe

So it would appear that it actually does work. The odd thing is that I had tried that originally the other day and got the same result you originally got (where it was showing “Professor.undefined undefined”) . Maybe there was a bug in some particular version of Typescript (or maybe if you transpile to a particular version of JavaScript)? Could even have been a Chrome bug?

2 Likes