Itzhak Galitch
Itzhak Galitch

Reputation: 376

How could I access to base class object to list its properties?

I have BaseEntity class that is inherited by Person class. How can I list base class properties (BaseEntity) in Person class.

class BaseEntity {
    _id: string;
    created: number;

constructor(id: string, created: number = Date.now()) {
    this._id = id;
    this.created = created;
    }
}

class Person extends BaseEntity {
    name: string;
    age: number;

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

    listBaseClassProperties() {
      //console.log(super); HOW CAN I DO THIS?
    }
}

When I tryied to console.log(super) in one of the derived class (Person) methods, I get undefined...

Upvotes: 0

Views: 512

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075755

This sounds like an X/Y problem, but addressing the question actually asked:

The object you're using doesn't differentiate between properties it got from the base class's code and properties it got from the derived class's code. They're just properties of the object. If you want to get a list of the properties the base class adds during initialization, you could do this immediately after calling super(); to get the names of all of the own, enumerable properties on the object at that point:

this.baseProperties = Object.keys(this);

...assuming you don't use TypeScript's automatic property initialization (which yo don't in the code in the question).

Then in listBaseClassProperties:

console.log(this.baseProperties.map(name => ({name, value: this[name]}));

...or any of several other ways you might use the list of names you got from Object.keys.

Of course, code in the base class can add a property any time, but that's strongly discouraged by TypeScript's static typing system, so getting the ones that exist immediately after initialization is probably Good Enough™. ;-)

Upvotes: 1

Related Questions