Search code examples
javascripttypescripttypescript-class

Why is this method in a class is not getting extended to the next class, instead I see - [Function (anonymous)] in TypeScript


register() works fine with the Person class and I do see the return statement when I console.log it after the Person class

Later on I am extending it to my Employee class but when I console.log it there, I see - [Function (anonymous)] instead of the return statement which I have set

here is the code :

interface PersonInterface {
  id: number;
  name: string;
  register(): string;
}

// Classes
class Person implements PersonInterface {
  id: number; 
  name: string;

  constructor(id: number, name: string) {
    this.id = id;
    this.name = name;
  }

  register() {
    return `${this.name} is now registered`;
  }
}

const mike = new Person(2, "Mike Jordan");

// console.log(mike.register()); - I get 'Mike Jordan is now registered'
   
class Employee extends Person {
  position: string;

  constructor(id: number, name: string, position: string) {
    super(id, name);
    this.position = position;
  }
}

const emp = new Employee(3, "Shawn", "Developer");

console.log(emp.register);

and this is what I see in the terminal for that console.log

[Function (anonymous)]

It seems like the method is not extended properly. How can I resolve this - the goal is to see the return statement just the same way that it works within the Person class


Solution

  • Now you are console logging

    console.log(emp.register);
    

    which returns:

    register() {
        return `${this.name} is now registered`;
    } 
    

    aka a function, if you add parenthesis

    console.log(emp.register());
    

    it will return

    "Shawn is now registered"